≅ Code

Just another WordPress.com weblog

Images and BLOB’s

Figuring out how to store an image as a blob in MySQL can be semi-confusing, here are some ways that I solved the problem:

If you are reading the image from the HD, pass the stream to setBinaryStream method of your prepared statement.

The code for this may look something like this:


try{
PreparedStatement statement = jdbcConnection.prepareStatement(
"insert into pictures(picture) values (?)");

File imageToRead = new File("c:\\Lime.jpg");
FileInputStream imageStream = new FileInputStream(imageToRead);

statement.setBinaryStream(1, imageStream);
statement.executeUpdate();
}
catch (Exception e)
{
e.printStackTrace();
}

If you already have an Image object this can be a difficult task to accomplish. So far I have found two ways to accomplish this task. The first way involves serializing the object and then writing that to the DB (Example shown below). The problem with this is that is severely shrinks the size of image you can use. The second way is to write the image to your hard disk and then use the technique shown above to place it in the DB.

The code to synchronize your object and then add it to the DB may look something like this (assume image is a valid java.awt.Image):


try{
//java.awt.Image is not serializable so you have to change it to an ImageIcon.
ImageIcon iconOfImage = new ImageIcon(image);

ObjectOutput outputPicture = new ObjectOutputStream(new FileOutputStream("image.ser"));
outputPicture.writeObject(iconOfImage);
outputPicture.close();

File serializedImage = new File("image.ser");
FileInputStream input = new FileInputStream(serializedImage);

PreparedStatement statement = jdbcConnection.prepareStatement(
"insert into pictures(picture) values (?)");
statement.setBinaryStream(1, input);
statement.executeUpdate();
}
catch (Exception e)
{
e.printStackTrace();
}

However, I would recommend saving the Image as a byte[]. That way it is to write to the DB and also to view as an Image. Code to write a byte[] to a blob is shown below (assume image is a valid byte[]).


try{
ByteArrayInputStream imageInputStream = new ByteArrayInputStream(image);

PreparedStatement statement = jdbcConnection.prepareStatement(
"insert into pictures(picture) values (?)");
statement.setBinaryStream(1, imageInputStream);
statement.executeUpdate();
}
catch (Exception e)
{
e.printStackTrace();
}

To convert the byte array to an image object to view use the following code (assume byteImage is a valid byte[])


Image image = Toolkit.getDefaultToolkit().createImage(byteImage);

Feel free to leave any comments or suggestions.

regards,

Chris

June 1, 2008 Posted by | Java, MySQL | , | 1 Comment

   

Follow

Get every new post delivered to your Inbox.