$maxwidth = 120;
$maxheight = 150;
$img = imagecreatefromjpeg($jpgimage);
//or imagecreatefrompng,imagecreatefromgif,etc. depending on user's uploaded file extension
$width = imagesx($img); //get width and height of original image
$height = imagesy($img);
//determine which side is the longest to use in calculating length of the shorter side, since the longest will be the max size for whichever side is longest.
if ($height > $width)
{
$ratio = $maxheight / $height;
$newheight = $maxheight;
$newwidth = $width * $ratio;
}
else
{
$ratio = $maxwidth / $width;
$newwidth = $maxwidth;
$newheight = $height * $ratio;
}
//create new image resource to hold the resized image
$newimg = imagecreatetruecolor($newwidth,$newheight);
$palsize = ImageColorsTotal($img); //Get palette size for original image
for ($i = 0; $i < $palsize; $i++) //Assign color palette to new image
{
$colors = ImageColorsForIndex($img, $i);
ImageColorAllocate($newimg, $colors['red'], $colors['green'], $colors['blue']);
}
//copy original image into new image at new size.
imagecopyresized($newimg, $img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagejpeg($newimg,$outputfile); //$output file is the path/filename where you wish to save the file.
//Have to figure that one out yourself using whatever rules you want. Can use imagegif() or imagepng() or whatever.
这将根据较长的一侧(宽度或高度)将任何图像按比例缩小到最大尺寸。它还会炸毁任何小于最大值的图像,您可以通过检查宽度和高度是否都小于最大值来停止。所以,200x300 的图片会缩小到 100x150,300x200 的图片会缩小到 120x80。
嗯,您希望宽度始终为 120,因此它会发生一些变化,是的,对于像 200x300 这样的图像,它必须剪掉一些东西,因为这样会缩小到 120x180 而不会出现任何失真,或者它必须进一步缩小它并将它的信箱,但这应该让你很好地开始。
Letterboxing 这个例子只需要弄清楚在 imagecopyresized() 函数中开始绘制新图像的正确 x 和 y 是什么。对于像 100x150 这样的东西,我认为 X 应该是 10,所以最后每边会有 10px 的空白空间用于 120x150。 Letterboxing 120x80 X 为 0,但 Y 为 35,因此 120x150 上下会有 35px 的空白空间。
您还希望使用 $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);
//Since you probably will want to set a color for the letter box do this
//Assign a color for the letterbox to the new image,
//since this is the first call, for imagecolorallocate, it will set the background color
//in this case, black rgb(0,0,0)
imagecolorallocate($newimg,0,0,0);
//Loop Palette assignment stuff here
imagecopyresized($newimg, $img, $writex, $writey, 0, 0, $newwidth, $newheight, $width, $height);
应该可以,还没试过。