$maxwidth = 120;
$maxheight = 150;
$img = imagecreatefromjpeg($jpgimage);
$width = imagesx($img);
$height = imagesy($img);
if ($height > $width)
{
$ratio = $maxheight / $height;
$newheight = $maxheight;
$newwidth = $width * $ratio;
}
else
{
$ratio = $maxwidth / $width;
$newwidth = $maxwidth;
$newheight = $height * $ratio;
}
$newimg = imagecreatetruecolor($newwidth,$newheight);
$palsize = ImageColorsTotal($img);
for ($i = 0; $i < $palsize; $i++)
{
$colors = ImageColorsForIndex($img, $i);
ImageColorAllocate($newimg, $colors['red'], $colors['green'], $colors['blue']);
}
imagecopyresized($newimg, $img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagejpeg($newimg,$outputfile);
这将按比例缩小任何图片,基于其中一边的最大尺寸(宽度或高度),同时将放大小于max的任何图像,并通过检查宽度和高度是否都小于其max值来停止。因此,200x300的图像将被缩小为100x150,而300x200的图像将被缩小为120x80。
嗯,您希望宽度始终为120,因此会有一些变化,并且,对于像200x300这样的图像,它必须删减一些内容,因为如果没有扭曲,它会缩小到120x180,或者必须进一步缩小并设置信封式黑边,但这应该可以很好地启动您。
在这个例子中,设置信封式黑边只涉及到在imagecopyresized()函数中找出开始绘制新图像的正确X和Y是多少。对于像100x150这样的情况,X可能会是10,因此在最终的120x150中,每侧会有10个像素的空白空间。设置信封式黑边120x80时,X将为0,但是Y将为35,因此在120x150上下各有35个像素的空白空间。
您还需要使用$maxwidth,$maxheight而不是$newwidth,$newheight创建$newimg,但是imagecopyresized()仍将同时使用$new值。
既然我很无聊,也没有其他事情可做,这些更改将完成它:
if ($height > $width)
{
$ratio = $maxheight / $height;
$newheight = $maxheight;
$newwidth = $width * $ratio;
$writex = round(($maxwidth - $newwidth) / 2);
$writey = 0;
{
else
{
$ratio = $maxwidth / $width;
$newwidth = $maxwidth;
$newheight = $height * $ratio;
$writex = 0;
$writey = round(($maxheight - $newheight) / 2);
}
$newimg = imagecreatetruecolor($maxwidth,$maxheight);
imagecolorallocate($newimg,0,0,0);
imagecopyresized($newimg, $img, $writex, $writey, 0, 0, $newwidth, $newheight, $width, $height);
那应该可以,但我还没有尝试过。