简体   繁体   中英

Convert image to byte array quickly

I am converting an image object into a byte array like this:

private byte[] getImageBytes() throws IOException {
    byte[] bytes;
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        ImageIO.write(copyImage(image), "png", baos);
        baos.flush();
        bytes = baos.toByteArray();
    }
    return bytes;
}

private BufferedImage copyImage(Image img) {
    BufferedImage copyOfImage = new BufferedImage(getSize().width, getSize().height, BufferedImage.TYPE_INT_RGB);
    Graphics g = copyOfImage.createGraphics();
    g.drawImage(img, 0, 0, getWidth(), getHeight(), null);
    return copyOfImage;
}

The problem is, that it takes more than 300ms to convert a 90KB image. If the image's size is around 1.2MB then the conversion takes only moderately longer (around 450ms). I have measured the time of the copyImage-method. It only takes around 1ms. The problem seems to be the ImageIO.write method.

Do you know of any way to speed this up?

In getImageBytes() you are compressing the image to PNG which can take time. The fastest ImageIO.write call you can achieve is

ImageIO.write(copyImage(image), "bmp", baos);

where there is no compression. Still, ImageIO contains reference implementations of image formats which are not designed for speed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM