0

I'm trying to generate thumbnails of the images my users upload. I have got the basic functionality to work by having my thumbnail class generate a thumbnail that is 50% of the width and height of the original image. However, I'd like to extend its functionality and enforce a hard limit on thumbnails that will be larger than 400px on either side after the 50% reduction.

This is what I have so far:

$x = $image_info[0]; // width of original image
$y = $image_info[1]; // height of original image
$x_t = $x/2; // width of 50% thumbnail
$y_t = $y/2; // height of 50% thumbnail
$biggest = ($x_t > $y_t) ? $x_t : $y_t; // determine the biggest side of the thumbnail

if($biggest > 400)
{
    // Enforce a 400px limit here

    /// somehow :(
}

With this hard limit, I want the original image to be scaled down so that no side exceeds 400px, and I want the other side to be scaled down relative so the image doesn't look distorted.

Being as terrible with math as I am, I can't work out a way to calculate the image dimensions that my thumbnail class should resize the image to.

Any ideas?

2 Answers 2

2

You'd have to compute a scaling factor:

$factor = $biggest / 400;  // if 503, then factor = 1.2575;

$new_x = $x / $factor;
$new_y = $y / $factor;

and use those two new dimensions for your scaling. That'll reduce whatever side is $biggest to 400, and proportionally reduce the other dimension to something less than 400.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but that doesn't seem to work. When I upload an image of size 2048/1216, the thumbnail comes out as: 800x475
Nevermind, fixed it. Had to do: $factor = $biggest/200;. Thanks! :)
0

You will have to check for each length, not both at once:

if ($x > 400) {
    $x_t = 400;
    $y_t = $y * (400 / $x);
}
if ($y > 400) {
    ...

If $x is 600 for example, the calucalation would become $y_t = $y * (400 / 600), thus reducing $y to 2/3 of its original value.

And add the same condition for the $y side. Additionally you might want to apply the calculations concurrently, if neither side is allowed to be larger than 400.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.