提问人:Andrew G. Johnson 提问时间:11/30/2008 最后编辑:Lightness Races in OrbitAndrew G. Johnson 更新时间:1/21/2013 访问量:1275
GD 缩略图生成器有问题
Having issues with GD thumbnail generator
问:
我正在使用 PHP 生成缩略图。问题是我有一个固定的宽度和高度,缩略图需要,而且图像经常被拉伸。
我想要的是图像保持相同的比例,并且对于高大的图像,在左侧和右侧或宽图像的顶部和底部都有黑色填充物(或任何颜色)。
这是我目前使用的代码:(为了可读性,稍微简化了一下)
$temp_image_file = imagecreatefromjpeg("http://www.example.com/image.jpg");
list($width,$height) = getimagesize("http://www.example.com/image.jpg");
$image_file = imagecreatetruecolor(166,103);
imagecopyresampled($image_file,$temp_image_file,0,0,0,0,166,103,$width,$height);
imagejpeg($image_file,"thumbnails/thumbnail.jpg",50);
imagedestroy($temp_image_file);
imagedestroy($image_file);
答:
0赞
da5id
11/30/2008
#1
看看这个上传类。它可以做你想要的,除此之外还有更多。
评论
0赞
Andrew G. Johnson
11/30/2008
不想做更多的事情,想做我要求的事情而没有额外的开销
2赞
Kevin Tighe
11/30/2008
#2
您需要计算新的宽度和高度以保持图像比例一致。查看此页面上的示例 2:
https://www.php.net/imagecopyresampled
评论
0赞
Andrew G. Johnson
11/30/2008
伟大!研究了功能并得到了我想要的,我稍后会发布源代码
1赞
Andrew G. Johnson
11/30/2008
#3
好的,让它工作,这是我最终所做的:
$filename = "http://www.example.com/image.jpg";
list($width,$height) = getimagesize($filename);
$width_ratio = 166 / $width;
if ($height * $width_ratio <= 103)
{
$adjusted_width = 166;
$adjusted_height = $height * $width_ratio;
}
else
{
$height_ratio = 103 / $height;
$adjusted_width = $width * $height_ratio;
$adjusted_height = 103;
}
$image_p = imagecreatetruecolor(166,103);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p,$image,ceil((166 - $adjusted_width) / 2),ceil((103 - $adjusted_height) / 2),0,0,ceil($adjusted_width),ceil($adjusted_height),$width,$height);
imagejpeg($image_p,"thumbnails/thumbnail.jpg",50);
1赞
Alnitak
12/22/2008
#4
这是我编写的一个函数,它接受 GD 图像对象、最大宽度、最大高度,并在这些参数内重新缩放:
function resized($im, $mx, $my) {
$x = $nx = imagesx($im);
$y = $ny = imagesy($im);
$ar = $x / $y;
while ($nx > $mx || $ny > $my) {
if ($nx > $mx) {
$nx = $mx;
$ny = $nx / $ar;
}
if ($ny > $my) {
$ny = $my;
$nx = $ny * $ar;
}
}
if ($nx != $x) {
$im2 = imagecreatetruecolor($nx, $ny);
imagecopyresampled($im2, $im, 0, 0, 0, 0, $nx, $ny, $x, $y);
return $im2;
} else {
return $im;
}
}
如果生成的图像不需要重新缩放,则它只返回原始图像。
0赞
CodeChap
2/25/2010
#5
这会将图像重新缩放为宽度和高度的较大尺寸,然后将其裁剪为正确的大小。
// Crete an image forced to width and height
function createFixedImage($img, $id=0, $preFix=false, $mw='100', $mh='100', $quality=90){
// Fix path
$filename = '../'.$img;
// Check for file
if(file_exists($filename))
{
// Set a maximum height and width
$width = $mw;
$height = $mh;
// Get new dimensions
list($width_orig, $height_orig) = getimagesize($filename);
$ratio_orig = $width_orig/$height_orig;
if ($width/$height < $ratio_orig) {
$width = $height*$ratio_orig;
}else{
$height = $width/$ratio_orig;
}
// Resample
$image_p = imagecreatetruecolor($mw, $mh);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
// Output
imagejpeg($image_p, "../images/stories/catalog/{$preFix}{$id}.jpg", $quality);
}
}
评论