开发者

PostgreSQL getting image from database

开发者 https://www.devze.com 2023-03-01 14:48 出处:网络
I have some Java code which get\'s an image from the database and saves it out to a file, however, when I open it in all p开发者_Go百科rograms but Photoshop I get an error similar to:

I have some Java code which get's an image from the database and saves it out to a file, however, when I open it in all p开发者_Go百科rograms but Photoshop I get an error similar to:

"It may be damaged or use a file format that Preview doesn’t recognize." - This paticular one is from preview on MAC. The database i'm pulling from is PostgreSQL and the column is a bytea.

My code is as follows:

public static void main(String[] args) throws Exception {
        Connection conn = null;
        try {
            conn = ConnectionManager.getConnection();

            String sql = "SELECT content from asset ";
            PreparedStatement stmt = conn.prepareStatement(sql);
            ResultSet resultSet = stmt.executeQuery();
            while (resultSet.next()) {

                File image = new File("/Users/esklein/testing"+UUID.randomUUID()+".jpg");
                FileOutputStream fos = new FileOutputStream(image);

                byte[] buffer = new byte[256];

                //
                // Get the binary stream of our BLOB data
                //
                InputStream is = resultSet.getBinaryStream("content");
                while (is.read(buffer) > 0) {
                    fos.write(buffer);
                }

                fos.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (conn != null && !conn.isClosed()) {
                conn.close();
            }
        }
    }

Any ideas why this isn't spitting out an image which can be opened in any file? Thanks


while (is.read(buffer) > 0) {

You're assuming that the read operation always fills the whole buffer. But if the data size is 1001 bytes, and the buffer size is 1000 bytes, then the last read will only get one byte. You need to check the number of bytes that was actually read, and then

fos.write(buffer, 0, bytesRead)
0

精彩评论

暂无评论...
验证码 换一张
取 消