Slow byte array for buffered image conversion

I have a simple server-side code that takes a byte array representing a JPEG image and returns the image sizes.

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

This works, but the problem is that it is unacceptably slow. For an image that is 100 KB, it takes 6 seconds. For an image that is 900KB, it takes 30 seconds. Was this expected? Is there a way to speed up the conversion of a byte array to buffereredImage?

FYI, capturing height / width is not the only thing I intend to do. Ultimately, I want to handle bufferedImage. So getting height / width was just an example of code.

+6
source share
3 answers

I think the problem may be that ImageIO uses disk caching by default (for a temporary file), even if your source is ByteArrayInputStream . Therefore, if your file system is slow, reading will also be slow, regardless of the input source.

You can disable disk caching (by using more memory) with ImageIO.setUseCache(false) . This will still cache your threads (to provide a reverse lookup), but only in memory.

It is also possible to set the cache directory to a specific path using ImageIO.setCacheDirectory(cacheDirectory) if you have a faster disk / ramdisk or similar store temporary files.

However, your read-time messages seem unreasonably high even for cache reading. If the problem persists, I suggest using the profiler to find out where the time is spent and see possible optimizations.

PS: I also have a custom ByteArrayImageInputStream , which can help reduce both disk access and memory consumption if this is really a problem.

+5
source

Where do you read the image from? Where does the byte [] come from? If you are reading an image with hdd, perhaps this will help to read it using BufferedInputStream .

This can speed up the download. But this only helps if you are reading a FileInputStream file. When reading from ByteArrayInputStream this will not help.

EDIT: Is there any other information that you could give us? Where does the byte array come from?

+2
source

Try running a java program with the following command line option and see if it speeds up at all:

 -Djava.awt.headless=true 
0
source

Source: https://habr.com/ru/post/958599/


All Articles