图像比较失败| java的

时间:2015-07-09 15:26:24

标签: java

    import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.IOException;
import java.net.URL;
public class Imagecompare
{
    public static void main(String args[])
      {
        BufferedImage img1 = null;
        BufferedImage img2 = null;
        try {
          URL url1 = new URL("http://www.desktopid.com/wp-content/uploads/2015/05/Apple-logo-Free-Desktop-Wallpapers.jpg");
          URL url2 = new URL("http://www.desktopid.com/wp-content/uploads/2015/05/Apple-logo-Free-Desktop-Wallpapers.jpg");
          img1 = ImageIO.read(url1);
          img2 = ImageIO.read(url2);
        } 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));
      }

}

这是一个比较两个图像并返回百分比差异的简单代码,但作为初学者,我在运行程序时遇到跟踪错误。

> javax.imageio.IIOException: Can't get input stream from URL!
    at javax.imageio.ImageIO.read(Unknown Source)
    at imager.Imagecompare.main(Imagecompare.java:16)
Caused by: java.io.IOException: Server returned HTTP response code: 403 for URL: http://www.desktopid.com/wp-content/uploads/2015/05/Apple-logo-Free-Desktop-Wallpapers.jpg
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at java.net.URL.openStream(Unknown Source)
    ... 2 more
Exception in thread "main" java.lang.NullPointerException
    at imager.Imagecompare.main(Imagecompare.java:21)

知道我做错了吗?是获取URL并传递它吗?任何帮助将不胜感激。

0 个答案:

没有答案