简体   繁体   中英

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);

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();

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. )

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM