antriver antriver - 3 months ago 12
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.

Thanks

Answer

Here's a logic behind cover calculations.

You have four base values :

imgWidth // your original img width
imgHeight

containerWidth // your container  width (here 698px)
containerHeight

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
finalHeight

So :

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

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

Comments