PHP GD - 如何修改我的缩略图创建器以从中心裁剪肖像图像?
这是我当前的代码:
$image = 'img.jpg';
$source = imagecreatefromjpeg($image);
list($origWidth, $origHeight) = getimagesize($image);
$imgH = 75;
$imgW = $origWidth / $origHeight * $imgH;
$thumb = imagecreatetruecolor($imgW, $imgH);
imagecopyresampled($thumb, $source, 0, 0, 0, 0, $imgW, $imgH, $origWidth, $origHeight);
这允许我输出固定高度为 75 像素的图像。我想做的是拥有 99x75
像素的恒定图像大小。不适合此的肖像图像将从中心被裁剪(因此原件的中心仍然是缩略图的中心 - 如果这有意义的话)。
我该怎么做?
Here is my current code:
$image = 'img.jpg';
$source = imagecreatefromjpeg($image);
list($origWidth, $origHeight) = getimagesize($image);
$imgH = 75;
$imgW = $origWidth / $origHeight * $imgH;
$thumb = imagecreatetruecolor($imgW, $imgH);
imagecopyresampled($thumb, $source, 0, 0, 0, 0, $imgW, $imgH, $origWidth, $origHeight);
This allows me to output an image with a fixed height of 75 pixels. What I would like to do is have a constant image size of 99x75
pixels. Portrait images that don't fit into this will be cropped from the center (so the center of the original remains the center of the thumbnail - if that makes sense).
How can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
嗯,这是纯粹的数学。您想要获得 99x75 的尺寸,并且只想从宽度上进行切割。因此,首先,调整大小以适应高度。这就是你所做的,但这样做是为了适合 75 的高度。将其切换到 99。然后检查宽度是否 <= 75。如果不是,那么你这样做:
所以,如果第一个之后的宽度“resize”是 100 而你想要 75,你计算 diff = 25,将其除以 2 并取 ceil => 13,然后你告诉GD函数从13开始复制图像,而不是0,并且仍然保持75高度。这意味着它将从宽度 13 复制到宽度 88 =>中心。
希望这是您想要的。
问候,
加布里埃尔
Well, it's pure math. You want to achieve a 99x75 size, and you want to only cut from the width. So first, you resize to fit the height. That's what you did, but did it to fit a height of 75. Switch it to 99. Then you, check for the width to be <= 75. If it's not then you do this:
So, if the width after the first "resize" is 100 and you wanted 75, you compute the diff = 25, split it by 2 and ceil it => 13, then you tell the GD function to start copying the image from 13, instead of 0, and still keep 75 height. This means it will copy from width 13 to witdh 88 => the center.
Hope this is what you wanted.
Regards,
Gabriel
此代码使用
imagecopy
函数进行复制源图像的 99x75px 区域。源宽度 - 99 / 2 返回开始复制的 x 坐标,源高度 - 75 / 2 返回 y 坐标。如果您有兴趣从任意大小的图像生成固定大小的缩略图,请查看 本文。This code uses
imagecopy
function to copy 99x75px region from the source image. Source width - 99 / 2 returns the x coordinate from which to start copying, Source height - 75 / 2 returns the y coordinate. If you are interested in generating fixed size thumbnails from arbitrary size images, have a look at this article.(未经测试)
(untested)