问题
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();
回答1:
This should work:
byte[] imageBytes = ((DataBufferByte) bufferedImage.getData().getDataBuffer()).getData();
回答2:
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();
}
回答3:
Try using:
ImageIO.setUseCache(false);
Before writing, maybe that helps.
回答4:
ByteArrayOutputStream baos;
ImageIO.write(bufferedImage, "png", baos);
byte[] imageBytes = baos.toByteArray();
回答5:
BufferedImage img = ImageIO.read(new ByteArrayInputStream(bytes));
byte[] bytes = new byte[buf.capacity()];
buf.get(bytes, 0, bytes.length);
回答6:
Use Apache Commons IO Utils Apache Commons
IOUtils.copy(inputStream,outputStream);
IO Utils API supports the large buffers easily
来源:https://stackoverflow.com/questions/10247123/java-convert-bufferedimage-to-byte-without-writing-to-disk