coobird / thumbnailator

Thumbnailator - a thumbnail generation library for Java
MIT License
5.08k stars 780 forks source link

ImageResize is taking longer time for Small images #193

Closed Augustusm007 closed 2 years ago

Augustusm007 commented 2 years ago

Expected behavior

Expecting image Resize processing time is lesser for small images than larger size Images.

Actual behavior

Smaller size Image took more time than larger size Image. Not sure of its due to height of the Image is playing any key role.

Steps to reproduce the behavior

Issue:

IMG1.JPG with size 4.64 MB with below dimensions took ~1 second to resize.

IMG1

Dimensions: 4224 x 2816 width: 4224 pixels Height: 2816 pixels Horizonal resolution: 300 dpi Vertical resolution: 300 dpi

IMG2.JPG with size 3.87 MB with below dimesions took ~13 seconds to resize.

Dimensions: 4480 x 6720 width: 4480 pixels Height: 6720 pixels Horizonal resolution: 72 dpi Vertical resolution: 72 dpi IMG2

Code snippet: ByteArrayOutputStream baos = new ByteArrayOutputStream(); Thumbnails.of(bais).height(600).width(500).toOutputStream(baos); byte[] data = baos.toByteArray();

Environment

coobird commented 2 years ago

@Augustusm007, I've taken a closer look at this.

This issue steps from the second image being a progressive JPEG, and the JPEG reader taking a longer time to process it. That is outside the scope of what Thumbnailator handles, however, I did find possible mitigation.

A bit more in detail of what I did:

First, I ran the two images on a default Java 8 installation and found similar results -- the second JPEG took a much longer time than the first.

To isolate whether this is an issue with Thumbnailator or the JPEG reader, I've added temporary timers in the code base and found that the JPEG reading stage was taking a long time.

Next, to isolate whether this is a problem with the JPEG reader bundled with Java, I also ran these images against TwelveMonkeys ImageIO JPEG reader and also found that the second image takes a longer time.

Finally, I went and took a closer look at the metadata of the two images and found that the second image is progressive JPEG. I suspected that this is the likely culprit.

To test this, I created an 4K image and saved one as a normal JPEG and another as a progressive JPEG. The conclusion was that the progressive one took longer to read in both Java's default JPEG reader and TwelveMonkeys.

That said, there is a bit of good news -- TwelveMonkeys JPEG reader was over twice as fast compared to the default one. Using it could be one mitigation measure for this issue.

coobird commented 2 years ago

Closing ticket as the root cause is outside the scope of Thumbnailator.

Augustusm007 commented 2 years ago

Thanks coobird !!