gpt4 book ai didi

java - java中从url加载图片

转载 作者:行者123 更新时间:2023-12-01 11:58:01 25 4
gpt4 key购买 nike

我使用过Windows 7操作系统,chrome/40.0.2214.93

我尝试使用java从url获取图像

我的java代码是

    public static void main(String[] args) {
// TODO Auto-generated method stub
BufferedImage img1 = null;
BufferedImage img2 = null;
InputStream inputstream=null;
URLConnection urlcon=null;
try {
URL url1 = new URL("http://rosettacode.org/mw/images/3/3c/Lenna50.jpg");
URL url2 = new URL("http://rosettacode.org/mw/images/b/b6/Lenna100.jpg");

urlcon=url1.openConnection();
urlcon.addRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36");

img1 = ImageIO.read(url1.openStream());
img2 = ImageIO.read(url2.openStream());
} catch (IOException e) {
e.printStackTrace();
}
int width1 = img1.getWidth(null);
int width2 = img2.getWidth(null);
int height1 = img1.getHeight(null);
int height2 = img2.getHeight(null);
if ((width1 != width2) || (height1 != height2)) {
System.err.println("Error: Images dimensions mismatch");
System.exit(1);
}
long diff = 0;
for (int y = 0; y < height1; y++) {
for (int x = 0; x < width1; x++) {
int rgb1 = img1.getRGB(x, y);
int rgb2 = img2.getRGB(x, y);
int r1 = (rgb1 >> 16) & 0xff;
int g1 = (rgb1 >> 8) & 0xff;
int b1 = (rgb1 ) & 0xff;
int r2 = (rgb2 >> 16) & 0xff;
int g2 = (rgb2 >> 8) & 0xff;
int b2 = (rgb2 ) & 0xff;
diff += Math.abs(r1 - r2);
diff += Math.abs(g1 - g2);
diff += Math.abs(b1 - b2);
}
}
double n = width1 * height1 * 3;
double p = diff / n / 255.0;
System.out.println("diff percent: " + (p * 100.0));
}

}

运行应用程序时出现错误

    java.io.IOException: Server returned HTTP response code: 403 for URL: http://rosettacode.org/mw/images/3/3c/Lenna50.jpg
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.URL.openStream(Unknown Source)
at ImgDiffPercent.main(ImgDiffPercent.java:32)
Exception in thread "main" java.lang.NullPointerException
at ImgDiffPercent.main(ImgDiffPercent.java:37)

我已经尝试了与此相关的堆栈流指南,但问题仍然没有解决。帮我解决一下。

谢谢...

最佳答案

我尝试了你的代码:

public static void main(String[] args) throws IOException {
BufferedImage image = ImageIO.read(new URL("http://rosettacode.org/mw/images/3/3c/Lenna50.jpg"));
}

我得到了和你一样的错误:

Exception in thread "main" javax.imageio.IIOException: Can't get input stream from URL!
Caused by: java.io.IOException: Server returned HTTP response code: 403 for URL: http://rosettacode.org/mw/images/3/3c/Lenna50.jpg

您收到的错误是由于服务器的 403 应答所致,而不是由于您的代码所致。

403 Forbidden :

服务器理解该请求,但拒绝满足它。授权不会有帮助,并且不应重复请求。如果请求方法不是 HEAD 并且服务器希望公开为什么请求没有被满足,它应该在实体中描述拒绝的原因。

关于java - java中从url加载图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28210397/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com