Search code examples
imagecompressionjpeggd

Detect JPG Compression Rate?


Normally when an image comes into my site I save it as jpg using an image library I wrote with the default quality of 80%. Now when I need to do some other operation on it (like cropping it, or even just resizing it) the image will be opened as jpg, processed, then saved back. However, if it has been compressed before I don't want to compress it again or else every time I need to do an operation the quality will fall.

Is there a way that I can detect how much the image has already been compressed before (in comparison to a png version of it I guess) using tools in the standard GD php libraries? I know that tools which detect where an image has been Photoshopped do so by comparing relative amounts of compression so I would think it is possible to detect the amount of compression but does anyone know how I would go about doing this calculation? Thanks.


Solution

  • You cannot get quality value from JPG. Moreover, the quality value is encoder dependent. It is not a standard or anything like this. Some programs have only (low, medium, high), in some 20 might be better than 90.

    Secondly, JPG simply will lose quality in each cosnequent encoding, even if you save it as best quality every time. Sad truth of life :) The only operations that do not worse the quality are flips and rotations (and crops, if they are aligned to JPEG block size).

    Rule of the thumb: Encode it every time at the same quality value. Example: If you save it once at let's say 60, then there is no gain if you save it at 80 next time. Just bigger file size.

    Also, try to reduce the number of such re-encodings and perform each manipulation on the original , if you have enough storage available.