Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a BufferedImage object into an InputStream or a BLOB?

I am trying to store an image uploaded by the user into the database with a LONGBLOB attribute... I ran into a problem with a PreparedStatement that has two methods to set a blob which are:

public void setBinaryStream(int parameterIndex, InputStream x)

public void setBlob(int parameterIndex, Blob x)

public void setBlob(int parameterIndex, InputStream inputStream)

Now the problem is I have a BufferedImage object which must be converted into Blob or InputStream to upload...

How can I do this without losing the original image format or quality?

like image 949
Asif Avatar asked Oct 04 '11 08:10

Asif


2 Answers

How can I do this without losing the original image format or quality?

You need to save it using some appropriate (lossless) format. The png format is one option.

The ImageIO class has methods for writing out an image to an output stream.

Here's a complete example of how you get hold of an InputStream from which you can read the PNG-representation of the content of a BufferedImage:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "png", baos);
InputStream is = new ByteArrayInputStream(baos.toByteArray());
like image 58
aioobe Avatar answered Oct 16 '22 20:10

aioobe


Here is a sample code:

ByteArrayOutputStream bas = new ByteArrayOutputStream();
ImageIO.write(image,"jpg", bas);
byte[] bytes = bas.toByteArray();
InputStream is = new ByteArrayInputStream(bytes);

Don't forget to check the second ImageIO.write parameter to your required image format (e.g. "jpg", "bmp", "png").

like image 43
Csujo Avatar answered Oct 16 '22 22:10

Csujo