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
ByteArrayOutputStream baos;
ImageIO.write(bufferedImage, "png", baos);
byte[] imageBytes = baos.toByteArray();
Use Apache Commons IO Utils Apache Commons
IOUtils.copy(inputStream,outputStream);
IO Utils API supports the large buffers easily
Try using:
ImageIO.setUseCache(false);
Before writing, maybe that helps.
The code below it's really fast (few milliseconds)
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public byte[] toByteArray(BufferedImage image) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(baos);
encoder.encode(image);
return baos.toByteArray();
}
This should work:
byte[] imageBytes = ((DataBufferByte) bufferedImage.getData().getDataBuffer()).getData();
BufferedImage img = ImageIO.read(new ByteArrayInputStream(bytes));
byte[] bytes = new byte[buf.capacity()];
buf.get(bytes, 0, bytes.length);