简体   繁体   English

PHP-缩小图片尺寸算法

[英]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. 我有一个php脚本,我想在div内显示一些图像,但是关于最大宽度和高度有一些限制。
For example, an image may have width=1000px and height=600px, but the max width and hight of the image should not be over 500 px in order to fit in the div. 例如,图像的宽度可能为1000px,高度为600px,但是图像的最大宽度和高度不得超过500 px,以适合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. 因此,我想转换尺寸以使图像适合div,但宽度和高度之间的比例保持不变。

Example: image dimensions: 1000x600, max-width = 500, max-height = 400. The result of the dimension shouldn't be 500x400 but 500x300. 示例:图像尺寸:1000x600,最大宽度= 500,最大高度=400。尺寸的结果不应为500x400,而应为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. 我写了一段代码,看起来似乎行得通,但是在有很多图像的情况下,它似乎在性能上工作不佳,因为这样做的目的是逐步减小大小10%,直到结果达到可接受的极限。

Any ideas? 有任何想法吗? Thank you in advance. 先感谢您。

This scales your values at maximum 2 times. 这最多可将您的值缩放2倍。

<?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? 1)正在进行多少缩放? If it's not very much, leaving it to CSS might be a good idea. 如果不是很多,最好将其留给CSS。

2) I presume you are using GD or ImageMagick or something? 2)我想您正在使用GD或ImageMagick或其他产品? 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM