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

≯℡__Kan透↙ 提交于 2019-11-28 05:53:15

This should work:

byte[] imageBytes = ((DataBufferByte) bufferedImage.getData().getDataBuffer()).getData();

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();
}

Try using:

ImageIO.setUseCache(false);

Before writing, maybe that helps.

BufferedImage img = ImageIO.read(new ByteArrayInputStream(bytes));
byte[] bytes = new byte[buf.capacity()];
buf.get(bytes, 0, bytes.length);
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

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