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% red开发者_如何学运维uction.
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?
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.
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.
精彩评论