Java – byte array buffer image conversion speed is slow

I have a simple server-side code that receives a byte array representing a JPEG image and returns the size of the image

public String processImage(byte[] data) {
    long startTime = System.currentTimeMillis();
    ByteArrayInputStream stream = new ByteArrayInputStream(data);
    BufferedImage bufferedImage;
    bufferedImage = ImageIO.read(stream);

    int height = bufferedImage.getHeight();
    int width = bufferedImage.getWidth();

    long endTime = System.currentTimeMillis();

    return "height="+height+" | width="+width+" | elapsed="+(endTime-startTime);
}

It works, but the problem is that it is unacceptably slow For 100kb images, it requires 6S For a 900 KB image, it takes 30 seconds Is this expected? Is there any way to make the bufferedimage conversion of byte arrays faster?

For reference only, grasping height / width is not the only thing I intend to do I finally want to deal with bufferedimage So getting height / width is just an example code

Solution

I think the problem may be related to the fact that imageio uses disk cache (temporary files) by default, even if your source is bytearrayinputstream Therefore, if your file system is slow, reading will be slow regardless of the input source

You can use imageio Setusecache (false) disables disk caching (at the expense of using more memory) This will still cache your stream (to allow backward searching), but only in memory

If you have a faster disk / ramdisk or similar temporary file for storage, you can also use imageio Setcachedirectory (cachedirectory) sets the cache directory to a specific path

That is, even for disk cache reads, the read time you report does not seem reasonable If the problem persists, I recommend using the analyzer to find out the time spent and look at possible optimizations

PS: I also have a custom bytearrayimageinputstream that may help reduce disk access and memory consumption if this is really a problem

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>