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

一世执手 提交于 2019-11-27 05:36:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!