phpimage-processing

Retrieve quality from previously generated webp image with imagewebp


I have a pretty complex script to handle image cropping/resizing in our custom CMS, built on native PHP 8.

I feel like I need to elaborate on my question first:

I'm cropping the images and saving them as .webp files to improve lighthouse scores, it works very well but I have 1 small issue which I hope you can help me with.

I'm saving images with the function imagewebp(image, dest, quality) and we made sure we can control the quality of images on a per image basis. So it's possible to crop one file to 70% quality and another at 90 if we want. The problem is changing the quality right now.

Every time a request to the cropper is made, it checks whether the original file is newer than the cached cropped version and if it's new, it will create a new cached version. Pretty standard stuff. But how would the cropper know if the quality was changed without making some major database changes?

Example:

We have image1.png, we view it at 500x500px with a quality of 70%. Now we want that image to be higher quality for some reason, let's say 90%. We change that. The next time a request to the cropper is made it checks the file dates, and since the original file isn't updated it also doesn't recrop the image, even though we want the quality to change.

My question: Is there any way for me to read the quality setting out of the cropped file? So I can see if it's changed and if so, recrop it.

I know I could probably do it with file names etc, but that would require some pretty big changes.


Solution

  • Other than lossless/lossy, I don't know of any field in a WEBP image that tells you the exact parameters that were used to encode it - specifically the quality. You can get that parameter with:

    webpinfo YOURIMAGE
    

    Rather than change the names of your files to record the encoding parameters, it is probably better to use Extended File Attributes to save that information alongside the file as that won't change your naming which might have significant implications for your app.