Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java- Convert bufferedimage to byte[] without writing to disk

I'm trying to send multiple images over a socket using java but I need a faster way to convert the images to a byte array so I can send them. I tried the following code but it wrote about 10,000 images to my C:\ drive. Is there a way to make this conversion without writing to disk? Thanks!

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();                      //ImageIO.setUseCache(false);                     ImageIO.write(bi.getImage(), "jpg", outputStream);                      byte[] imageBytes = outputStream.toByteArray(); 
like image 990
tier1 Avatar asked Apr 20 '12 13:04

tier1


People also ask

How do I save BufferedImage in Java?

The formatName parameter selects the image format in which to save the BufferedImage . try { // retrieve image BufferedImage bi = getMyImage(); File outputfile = new File("saved. png"); ImageIO. write(bi, "png", outputfile); } catch (IOException e) { ... }

How do you convert a byte array into a string?

There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.

What is BufferedImage in Java?

A BufferedImage is comprised of a ColorModel and a Raster of image data. The number and types of bands in the SampleModel of the Raster must match the number and types required by the ColorModel to represent its color and alpha components. All BufferedImage objects have an upper left corner coordinate of (0, 0).


1 Answers

This should work:

byte[] imageBytes = ((DataBufferByte) bufferedImage.getData().getDataBuffer()).getData(); 
like image 147
stacker Avatar answered Sep 21 '22 17:09

stacker