GD 缩略图生成器出现问题
我正在使用 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);
I'm using PHP to generate thumbnails. The problem is that I have a set width and height the thumbnails need to be and often times the images are stretched.
What I'd like is the image to remain at the same proportions and just have black filler (or any color) either on the left & right for tall images or top & bottom for wide images.
Here is the code I'm currently using: (dumbed down a bit for readability)
$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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
好吧,它工作了,这就是我最终所做的:
Okay got it working, here's what I ended up doing:
这是我编写的一个函数,它接受 GD 图像对象、最大宽度、最大高度,并在这些参数内重新缩放:
如果生成的图像不需要重新缩放,则它只返回原始图像。
Here's a function I wrote that takes a GD image object, max width, max height, and rescales within those parameters:
If the resulting image doesn't need rescaling then it just returns the original image.
看看这个上传类。 它可以满足您的需求,而且还可以做更多的事情。
Have a look at this upload class. It does what you want and a lot more besides.
这会将图像重新缩放为宽度和高度的较大尺寸,然后将其裁剪为正确的尺寸。
This rescales the image to the larger size of the width and height and then crops it to the correct size.
您需要计算新的宽度和宽度。 高度以保持图像比例。 查看本页上的示例 2:
https://www.php.net/imagecopyresampled
You'll need to calculate the new width & height to keep the image proportionat. Check out example 2 on this page:
https://www.php.net/imagecopyresampled