PHP 裁剪图像以固定宽度和高度而不丢失尺寸比例

2024-06-19

我希望创建尺寸为 100 像素 x 100 像素的缩略图。我看过很多解释这些方法的文章,但如果要保持尺寸比,大多数文章最终都会有宽度!=高度。

例如,我有一个 450 像素 x 350 像素的图像。我想裁剪为 100px x 100px。如果我保持这个比例,我最终会得到 100 像素 x 77 像素。当我在行和列中列出这些图像时,这使得它变得很难看。然而,没有尺寸比例的图像看起来也会很糟糕。

我看过 flickr 上的图片,它们看起来棒极了。例如:
缩略图:http://farm1.static.flickr.com/23/32608803_29470dfeeb_s.jpg http://farm1.static.flickr.com/23/32608803_29470dfeeb_s.jpg
中等大小:http://farm1.static.flickr.com/23/32608803_29470dfeeb.jpg http://farm1.static.flickr.com/23/32608803_29470dfeeb.jpg
大尺寸:http://farm1.static.flickr.com/23/32608803_29470dfeeb_b.jpg http://farm1.static.flickr.com/23/32608803_29470dfeeb_b.jpg

tks


这是通过仅使用图像的一部分作为缩略图来完成的,该缩略图具有 1:1 的宽高比(主要是图像的中心)。如果你仔细观察,你可以在 flickr 缩略图中看到它。

因为你的问题中有“作物”,我不确定你是否已经知道这一点,但是你想知道什么呢?

要使用裁剪,下面是一个示例:

//Your Image
$imgSrc = "image.jpg";

//getting the image dimensions
list($width, $height) = getimagesize($imgSrc);

//saving the image into memory (for manipulation with GD Library)
$myImage = imagecreatefromjpeg($imgSrc);

// calculating the part of the image to use for thumbnail
if ($width > $height) {
  $y = 0;
  $x = ($width - $height) / 2;
  $smallestSide = $height;
} else {
  $x = 0;
  $y = ($height - $width) / 2;
  $smallestSide = $width;
}

// copying the part into thumbnail
$thumbSize = 100;
$thumb = imagecreatetruecolor($thumbSize, $thumbSize);
imagecopyresampled($thumb, $myImage, 0, 0, $x, $y, $thumbSize, $thumbSize, $smallestSide, $smallestSide);

//final output
header('Content-type: image/jpeg');
imagejpeg($thumb);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

PHP 裁剪图像以固定宽度和高度而不丢失尺寸比例 的相关文章

随机推荐