如何在 PHP 中保持宽高比的同时将图像调整为固定宽度和高度?
How do I Resize images to fixed width & height while maintaing aspect ratio in PHP?
我正在尝试在 PHP
中将图像批量调整为 250 x 250 的大小
所有源图像都大于 250 x 250,这很有帮助。
我想保持宽高比,但将它们全部设为 250 x 250。我知道为此会裁掉一部分图像。这对我来说不是问题
问题是我当前的脚本仅适用于宽度并根据纵横比确定高度,但有时,图像现在最终会变成 250 x 166。我无法使用它。
因此需要以相反的方式调整大小(高度到宽度)
脚本看起来如何始终使最终图像不拉伸为 250 x 250。同样,我不在乎是否有裁剪。我假设某个地方会有其他人,但现在我已经无法理解了。我更像是一个前端人员。
任何帮助都会很棒。
以下是我完整脚本的相关部分:
$width = 250;
$height = true;
// download and create gd image
$image = ImageCreateFromString(file_get_contents($url));
// calculate resized ratio
// Note: if $height is set to TRUE then we automatically calculate the height based on the ratio
$height = $height === true ? (ImageSY($image) * $width / ImageSX($image)) : $height;
// create image
$output = ImageCreateTrueColor($width, $height);
ImageCopyResampled($output, $image, 0, 0, 0, 0, $width, $height, ImageSX($image), ImageSY($image));
// save image
ImageJPEG($output, $destdir, 100);
$newWidth = 250;
$newHeight = 250;
// download and create gd image
$image = ImageCreateFromString(file_get_contents($url));
$width = ImageSX($image);
$height = ImageSY($image);
$coefficient = $newHeight / $height;
if ($newHeight / $width > $coefficient) {
$coefficient = $newHeight / $width;
}
// create image
$output = ImageCreateTrueColor($newWidth, $newHeight);
ImageCopyResampled($output, $image, 0, 0, 0, 0, $width * $coefficient, $height * $coefficient, $width, $height);
// save image
ImageJPEG($output, $destdir, 100);
我正在尝试在 PHP
中将图像批量调整为 250 x 250 的大小所有源图像都大于 250 x 250,这很有帮助。
我想保持宽高比,但将它们全部设为 250 x 250。我知道为此会裁掉一部分图像。这对我来说不是问题
问题是我当前的脚本仅适用于宽度并根据纵横比确定高度,但有时,图像现在最终会变成 250 x 166。我无法使用它。
因此需要以相反的方式调整大小(高度到宽度)
脚本看起来如何始终使最终图像不拉伸为 250 x 250。同样,我不在乎是否有裁剪。我假设某个地方会有其他人,但现在我已经无法理解了。我更像是一个前端人员。
任何帮助都会很棒。
以下是我完整脚本的相关部分:
$width = 250;
$height = true;
// download and create gd image
$image = ImageCreateFromString(file_get_contents($url));
// calculate resized ratio
// Note: if $height is set to TRUE then we automatically calculate the height based on the ratio
$height = $height === true ? (ImageSY($image) * $width / ImageSX($image)) : $height;
// create image
$output = ImageCreateTrueColor($width, $height);
ImageCopyResampled($output, $image, 0, 0, 0, 0, $width, $height, ImageSX($image), ImageSY($image));
// save image
ImageJPEG($output, $destdir, 100);
$newWidth = 250;
$newHeight = 250;
// download and create gd image
$image = ImageCreateFromString(file_get_contents($url));
$width = ImageSX($image);
$height = ImageSY($image);
$coefficient = $newHeight / $height;
if ($newHeight / $width > $coefficient) {
$coefficient = $newHeight / $width;
}
// create image
$output = ImageCreateTrueColor($newWidth, $newHeight);
ImageCopyResampled($output, $image, 0, 0, 0, 0, $width * $coefficient, $height * $coefficient, $width, $height);
// save image
ImageJPEG($output, $destdir, 100);