【发布时间】:2020-04-20 19:46:04
【问题描述】:
我目前有一个脚本,用户可以在其中上传任何尺寸的图像文件。 上传的图像通过 ajax 发送到 PHP 脚本,在该脚本中应该调整大小并保存到服务器。 调整大小的过程不应裁剪或扭曲图像,而是通过在侧面添加白色或顶部/底部(如果与尺寸不完全匹配)将其调整到特定尺寸。我有这个过程非常适合方形图像 - 但是当尝试修改过程以适用于矩形尺寸时,它不再正常工作。
$sourceImage = imagecreatefromjpeg("../img/whiteBG.jpg");
$dimensions = getimagesize($files["tmp_name"][$i]);
$ratio = $dimensions[0] / $dimensions[1]; // width/height
$dst_y = 0;
$dst_x = 0;
//final image should be 600x360
if ($ratio > 1) {
$width = 600;
$height = 360 / $ratio;
$dst_y = (360 - $height) / 2;
} else {
$width = 600 * $ratio;
$height = 360;
$dst_x = (600 - $width) / 2;
}
$src = imagecreatefromstring(file_get_contents($files["tmp_name"][$i]));
$dst = imagecreatetruecolor($width, $height);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $width, $height, $dimensions[0], $dimensions[1]);
imagecopymerge($sourceImage, $dst, $dst_x, $dst_y, 0, 0, imagesx($dst), imagesy($dst), 100);
$moved = imagepng($sourceImage, $dir . $filename);
输出图像 ($moved) 的最终尺寸应为 600 x 360。相反,最终图像总是失真的。如果上传的图片比例较高,则最终产品会拉伸宽度。如果上传更宽的图像比例,则它会被压缩并以额外的顶部和底部间距混合。 whiteBG.jpg 只是一个尺寸为 600x360 的纯白色 jpeg
【问题讨论】: