$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.
这将根据较长的一侧(宽度或高度)按比例缩小任何图像,以达到最大尺寸.它还会炸掉任何小于最大值的图像,您可以通过检查宽度和高度是否小于最大值来停止.因此,200×300图像将缩小至100×150,300×200图像将缩小至120×80.
嗯,你想要宽度总是120,所以它会改变一点,是的,它必须在像200×300的图像的情况下削减一些东西,因为它会缩小到120×180没有任何失真,或者它会必须将它缩小得更远,并将信箱装箱,但这应该让你开始很好.
Letterboxing这个例子只需要弄清楚在imagecopyresized()函数中开始绘制到新图像的正确x和y是什么.在像100×150这样的情况下,我认为X将是10,所以最终每侧有10px的空白区域为120×150. Letterboxing 120×80 X将为0但Y将为35,因此对于120×150,上下将有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);
这应该工作,尚未尝试过.