从数据库比较图像时出错

时间:2013-11-22 08:24:21

标签: java sql compare blob photo

我想将导入的图像与数据库中的图像进行比较。到目前为止,我已经创建了这个,但我一直收到错误:

Uncaught error fetching image:
java.lang.NullPointerException
    at java.io.FileInputStream.<init>(FileInputStream.java:103)
    at java.io.FileInputStream.<init>(FileInputStream.java:66)
    at sun.awt.image.FileImageSource.getDecoder(FileImageSource.java:35)
    at sun.awt.image.InputStreamImageSource.doFetch(InputStreamImageSource.java:240)
    at sun.awt.image.ImageFetcher.fetchloop(ImageFetcher.java:172)
    at sun.awt.image.ImageFetcher.run(ImageFetcher.java:136)

这是我的代码:

String file1 = "C:\\Users\\Seth\\Desktop\\Capstone\\bill.jpg";
String file2;

public void DBImages() throws ClassNotFoundException, SQLException {

    String url = "jdbc:oracle:thin:@localhost:1521:ORCL";
    Connection conn = null;
    Class.forName("oracle.jdbc.driver.OracleDriver");
    conn = DriverManager.getConnection(url, "c##lambros", "16111111");
    String sql = "SELECT foto FROM criminals WHERE criminal_id = 1";
    PreparedStatement stmt = conn.prepareStatement(sql);
    ResultSet rset = stmt.executeQuery();
    byte[] bytes = null;
    while (rset.next()) {

        bytes = rset.getBytes(1);
        file2 = bytes.toString();
        processImage();
    }
}


public void processImage() {


    Image image1 = Toolkit.getDefaultToolkit().getImage(file1);
    Image image2 = Toolkit.getDefaultToolkit().getImage(file2);

    try {

        PixelGrabber grab1 = new PixelGrabber(image1, 0, 0, -1, -1, false);
        PixelGrabber grab2 = new PixelGrabber(image2, 0, 0, -1, -1, false);

        int[] data1 = null;

        if (grab1.grabPixels()) {
            int width = grab1.getWidth();
            int height = grab1.getHeight();
            data1 = new int[width * height];
            data1 = (int[])grab1.getPixels();
        }

        int[] data2 = null;

        if (grab2.grabPixels()) {
            int width = grab2.getWidth();
            int height = grab2.getHeight();
            data2 = new int[width * height];
            data2 = (int[])grab2.getPixels();
        }

        System.out.println("Pixels equal: " + java.util.Arrays.equals(data1, data2));

    } catch (InterruptedException e1) {
        e1.printStackTrace();
    }
}

public static void main(String args[]) {
    CompareImage compare = new CompareImage();
    compare.processImage();
}

我认为我的逻辑是正确的。为什么该方法无法从数据库中获取图像?

1 个答案:

答案 0 :(得分:1)

你的行

file2 = bytes.toString();

完全错了。它绝不会将字节写入文件。你显然没有用Java做任何文件IO。

如果你有足够的内存,你可以绕过文件写入。您可以将byte[]打包到ByteArrayInputStream并使用ImageIO.read()来获取图片。

InputStream in = new ByteArrayInputStream(bytes);
Image img = ImageIO.read(in);