user1727939
user1727939

Reputation:

Java: How To Convert Image to Byte[]

I'm having an image in Database in bytearray format. I want to display on browser. I don't know how to write Image using OutputStream. Here is my code.

   byte[] imageInBytes = (byte[]) obj; // from Database
    InputStream in = new ByteArrayInputStream(imageInBytes);
    Image img = ImageIO.read(in).getScaledInstance(50, -1, Image.SCALE_SMOOTH);


    OutputStream o = resp.getOutputStream();    // HttpServletResponse
    o.write(imgByte);

Upvotes: 2

Views: 7596

Answers (3)

Siva Tumma
Siva Tumma

Reputation: 1701

You have to set the content type of the response to be an image type that you are sending. Suppose your image was stored when it was a jpeg. then,

OutputStream o = resp.getOutputStream();    // HttpServletResponse
o.setContentType("image/jpeg");
o.write(img.getBytes() /* imgByte */);

would send the browser an image. ( The browser understands from the header information that the following information you just sent it, is a jpeg image. )

Upvotes: 1

MadProgrammer
MadProgrammer

Reputation: 347332

You could try using ImageIO.write...

ImageIO.write(img, "jpg", o);

But this will require you to use BufferedImage when reading...

BufferedImage img = ImageIO.read(in);

You could then use AffineTransform to scale the image...

BufferedImage scaled = new BufferedImage(img.getWidth() / 2, img.getHeight() / 2, img.getType());
Graphics2D g2d = scaled.createGraphics();
g2d.setTransform(AffineTransform.getScaledInstance(0.5, 0.5));
g2d.drawImage(img, 0, 0, null);
g2d.dispose();

img = scaled;

This, obviously, only scales the image by 50%, so you'll need to calculate the required scaling factor based on the original size of the image against your desired size...

Take a look at Java: maintaining aspect ratio of JPanel background image for some ideas on scaling images...

Upvotes: 0

Rahul Tripathi
Rahul Tripathi

Reputation: 172628

You may try something like this:

File f=new File("image.jpg");
BufferedImage o=ImageIO.read(f);
ByteArrayOutputStream b=new ByteArrayOutputStream();
ImageIO.write(o, "jpg", b);
byte[] img=b.toByteArray();

Upvotes: 1

Related Questions