antriver antriver - 1 month ago 5x
CSS Question

What's the math behind CSS's background-size:cover

I'm creating an "image generator" where users can upload an image and add text and/or draw on it. The outputted image is a fixed size (698x450).

On the client side, when the user uploads their image it is set as the background of a div that's 698x450 with background-size:cover. This makes it fill the area nicely.

The final combined image is generated by PHP using GD functions. My question is, how can I get the image to scale in PHP the same way it does in CSS. I want the result of the PHP script to look the same as if the image was set in CSS as it was above.
Does anyone know how browsers using background-size:cover calculate how to scale the image appropriately? I want to translate this into PHP.



Here's a logic behind cover calculations.

You have four base values :

imgWidth // your original img width

containerWidth // your container  width (here 698px)

Two ratios derived from these values :

imgRatio = (imgHeight / imgWidth)       // original img ratio
containerRatio = (containerHeight / containerWidth)     // container ratio

You want to find two new values :

finalWidth // the scaled img width

So :

if (containerRatio > imgRatio) 
    finalHeight = containerHeight
    finalWidth = (containerHeight / imgRatio)
    finalWidth = containerWidth 
    finalHeight = (containerWidth / imgRatio)

... and you have the equivalent of a background-size : cover.