$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 без каких-либо искажений, или потребуется уменьшить его еще больше и пометить его почтовыми ящиками, но это поможет вам начать хорошо.
Создание почтовых ящиков в этом примере просто потребует выяснения, какими будут правильные x и y для начала рисования нового изображения в функции imagecopyresized ().В случае чего-то вроде 100x150, X будет 10, я думаю, так что с каждой стороны будет 10px пустого пространства для 120x150 в конце.Размер почтового ящика 120x80 X будет 0, но Y будет 35, поэтому для 120x150 будет 35 пикселей пустого пространства выше и ниже.
Вы также хотели бы сделать $ newimg с $ maxwidth, $ maxheight, а не $newwidth, $ newheight, но 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);
Это должно сработать, еще не пробовал.