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();
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) { ... }
There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.
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).
This should work:
byte[] imageBytes = ((DataBufferByte) bufferedImage.getData().getDataBuffer()).getData();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With