Question

I am working around my project and got some Problem, I searched for it , but couldn't find meaning full learning resource, What I need is to Store Image in SQL Server Database using my Java program , and will need that Back to Retrieve, images are not of larger size they are ranging between 30 and 50 K, I can load images from my Disk by using getImage() method in toolKit

Image imm = Toolkit.getDefaultToolkit().getImage("URl");

, but i don't know How to convert that image to Binary Format and to store in Database, and then retrieve Back From Database. I want to Store that in VarBinary s by looking around several sites i found that the image type in SQL Server is soon going to Retire.

Was it helpful?

Solution

While it's not a good idea to store very large binary objects in the database, the Microsoft research paper "To BLOB or Not To BLOB: Large Object Storage in a Database or a Filesystem" indicates it's an efficient approach if object sizes are less than 256K. So it sounds like you've hit the sweet spot for database storage with 30K images.

You can load your image as a buffered image from a URL using:

BufferedImage imm = ImageIO.read(url);

Then convert it to a byte array with:

byte[] immAsBytes = 
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//use another encoding if JPG is innappropriate for you
ImageIO.write(imm, "jpg", baos );
baos.flush();
byte[] immAsBytes = baos.toByteArray();
baos.close();

Then store the byte array as recommended by this article as a VARBINARY in the database. In your JDBC code, you should wrap the byte array in a ByteArrayInputStream and set the PreparedStatement parameter as a BinaryStream:

PreparedStatement pstmt = commection.prepareStatement("INSERT INTO IMAGES (image) VALUES(?)");
ByteArrayInputStream bais = new ByteArrayInputStream(immAsBytes);
pstmt.setBinaryStream(1, bais, immAsBytes.length);
pstmt.executeUpdate();
pstmt.close();

To get the image out of the database, use ResultStatement.getBlob():

Blob immAsBlob = rs.getBlob();
byte[] immAsBytes = immAsBlob.getBytes(1, (int)immAsBlob.length()));

Finally, convert the byte array to a BufferedImage and do something with it:

InputStream in = new ByteArrayInputStream(immAsBytes);
BufferedImage imgFromDb = ImageIO.read(in);

OTHER TIPS

It is generally not a very good idea to put into the database large resources like images, unless you really need ACID compliance when working with them. Database dumps and time required to produce them grow tremendously and you will need to use the more complex and fragile incremental backups.

Generally it may be more efficient to store the images on the filesystem, and only put the image path to the database after you are sure the image resource has been successfully created.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top