php - reduce image dimensions algorithm
i have a php script where i want to display some images inside a div, but there are some restrictions regarding the max width and height.
For example, an image may have width=1000px and height=600px,开发者_Python百科 but the max width and hight of the image should not be over 500 px in order to fit in the div. So, i want to convert the dimensions so that the image fits in the div but the ratio between width and height remains the same.Example: image dimensions: 1000x600, max-width = 500, max-height = 400. The result of the dimension shouldn't be 500x400 but 500x300.
I've wrote a piece of code that seems to be working, but it doesn't seem to be working well in terms of performance when there are lots of images, as it does something like reducing the size by 10% step-by-step until the result is in the accepted limit.
Any ideas? Thank you in advance.
This scales your values at maximum 2 times.
<?php
define('MAX_WIDTH', 500);
define('MAX_HEIGHT', 200);
function scale($w, $h)
{
$rw = $w; $rh = $h; $factor = 0.0;
if( $rw > MAX_WIDTH )
{
$factor = $rw / MAX_WIDTH;
$rw = MAX_WIDTH;
$rh = floor($factor * $rh);
}
if( $rh > MAX_HEIGHT )
{
$factor = $rh / MAX_HEIGHT;
$rh = MAX_HEIGHT;
$rw = floor($factor * $rw);
}
return array($rw, $rh);
}
echo explode('x', scale(1000, 500));
?>
It will not be a good idea to resize your images dynamically every time a user access your page.
Depending on the script that you are using,like this one, you will need to resize all your images first and save them, so you won't have the overhead everytime someone access your page.
Show some of the code you have so far, maybe it can be improved
It's not quite clear what you're asking.
1) How much scaling is going on? If it's not very much, leaving it to CSS might be a good idea.
2) I presume you are using GD or ImageMagick or something? Perhaps you are after something like this:
function scale($x,$y,$maxX, $maxY) {
if ($x > $maxX) return array($maxX, $maxX / $x * $y);
else return array($x, $y);
}
...
<declare variables $toScaleX, $toScaleY, $maxX, $maxY>
list($x, $y) = scale($toScaleX, $toScaleY, $maxX, $maxY);
list($x, $y) = scale($y, $x, $maxY, $maxX);
<$x, $y, are now the desired dimensions to scale to>
精彩评论