Get information about image-color

i stumbled upon some of the kirby built in functions related to images and im wondering if there is a way to check if an image is either darker then 50% black or brighter ?

would be awesome for overlay text wich could be adapted in brightness depending on underlying image.

I did this some time ago for a photography website with a fullscreen slider. There’s nothing built in to Kirby, but it’s only a few lines of code…

PHP’s imagecolorat() returns the rgb value of a certain pixel of an image. If you loop over the image’s pixels and calculate each pixel’s luminance, e. g. using the formular from this article, and divide their sum by the total number of pixels, you’ll get the image’s average luminance (from 0 to 255).

looks good. how does this solution perform when using multiple large images ?
Have you tried imagecopyresampled() to create a 1px by 1px image ? the generated image is colored with the average color.

Looping over all pixels is probably not very efficient, especially not if you are doing this on every request.
Resampling the image to 1x1 pixels and getting the luminance from it should work fine (if you cache the result). But keep in mind that this doesn’t check for a specific image region but for the whole image. Images with dark and bright parts won’t work.

1 Like