【发布时间】:2012-11-08 19:19:31
【问题描述】:
我正在尝试缩小用户在上传时上传的图片。
这没问题,但我现在想具体说明尺寸。
我正在寻找一些关于我努力生成的算法的建议,该算法将采用任何形状的图像 - 任何宽度/高度的正方形或矩形并缩小它。
此图像需要缩小到目标框大小(这会发生变化,但存储在变量中)..
所以它需要缩小图像,使宽度和高度都大于目标的宽度和高度,保持纵横比。但只是..
目标尺寸将用于裁剪图像,因此边缘等周围没有空白。
我正在寻找基于不同尺寸图像创建正确调整大小背后的算法 - 我可以处理裁剪,甚至在大多数情况下调整大小,但它在少数情况下失败,所以我伸出手来。
我并不是真的要求 PHP 代码更伪。显然两者都可以。
非常感谢。
当前代码.. 但我已经经历了这么多迭代,这可能不再适用了.. :P
$image = $image_orig->clone();
$wRatio = $imageprops['width'] / $dimensions[0]; // imageprops = original image dimens.
$hRatio = $imageprops['height'] / $dimensions[1]; // $dimensions[0] = new width
$maxRatio = max($wRatio,$hRatio); // $dimensions[1] = new height
var_dump('thumb');
$ratio = ($imageprops['width'] - $dimensions[0]) > ($imageprops['height'] - $dimensions[1]);
$shape = ($imageprops['width'] > $imageprops['height']);
$error = ($imageprops['width'] / $imageprops['height']);
if( $error < 0.95 || $error > 1.05 ) { // its NOT a square
if($shape){ // longer width
$scale = $imageprops['height'] / $dimensions[0];
var_dump('1');
$height = $imageprops['height'] / $scale;
$image->scaleImage(0, $height);
} else {
$scale = $imageprops['width'] / $dimensions[1];
var_dump('2');
$width = $imageprops['width'] / $scale;
$image->scaleImage($width, 0);
}
} elseif($ratio) { // is square
$scale = $imageprops['height'] / $dimensions[1];
$newWidth = $imageprops['width'] / $scale;
$extra = 0;
$height = $dimensions[1]+$extra;
$image->scaleImage(0, $height);
} else {
$scale = $imageprops['width'] / $dimensions[0];
$newHeight = $imageprops['height'] / $scale;
$extra = 0;
$width = $dimensions[0]+$extra;
$image->scaleImage($width, 0);
}
$image_size = $image->getImageGeometry();
$image->cropImage($dimensions[0], $dimensions[1],($image_size['width']-$dimensions[0])/2,($image_size['height']-$dimensions[1])/2);
【问题讨论】:
-
你大概已经知道了盒子的尺寸,所以只在 resize 调用中使用它们?还是您的意思是要按比例调整大小,以免图像失真?
-
假设我有一个 600w x 457h,我希望它达到 120x90.. 保持原始的纵横比。在这种情况下,如果我按比例将 457 减小到 90,则宽度会达到 118 .. 太小了。现在对于某些图像,这可行,但对于此图像,我必须使用宽度作为调整大小的起始尺寸。但我需要一种适用于所有图像尺寸的算法。
-
我真的很生气你没有在你原来的问题中包含这些信息。你刚刚发布的内容完全改变了原帖的原意,我刚刚花了最后 15分钟写一个可靠的答案,这根本不是你需要的。
-
真的很抱歉。我累了——天色已晚。随意张贴。它可能仍然有用。
标签: php algorithm imagemagick crop pseudocode