gulp-imagemin icon indicating copy to clipboard operation
gulp-imagemin copied to clipboard

Keep original input file if optimized version is larger (or "already optimized")

Open MCStreetguy opened this issue 2 years ago • 1 comments

I noticed a strange behavior with the plugin today. While running several JPEG images through it, I noticed that the file size had effectively more than doubled after the conversion. Some images went from ~280kB to ~800kB, in the worst case an image went from 1.8MB to 4.7MB, so mostly by a factor of about 2.5 times. I then experimented a bit with the options and also swapped out different JPEG plugins for testing, but this merely increased the file size further. The verbose output of the plugin did indeed say "already optimized" for all of those in any case.

Nevertheless, the "optimized" version was saved, although the input had obviously already been optimized and the conversion had caused the size to explode. After a short look into the source code I saw that in line 94 of index.js the output of Imagemin is written unconditionally into the stream, although shortly before there is a check if any data has been reduced at all.

Is there a reason that despite the increased amount of data, the new version is saved here instead of the original smaller version? I would have expected exactly this, that an already optimized image is not optimized again. Alternatively, would it be possible to add an option to influence this behavior? For example, a boolean flag "keepAlreadyOptimized" or something similar next to the existing "verbose" option, which prevents overwriting the file if the original is smaller. This way you could at least choose which variant would make more sense for your own project.

I'm happy to open a pull request myself with the appropriate change if there are no objections to my suggestion.

MCStreetguy avatar Dec 28 '21 13:12 MCStreetguy

I have experienced several times that the image size increases, so having that feature would be very helpful.

sapics avatar Apr 27 '22 13:04 sapics