这里有几个问题。首先,您不应该创建具有指定新高度和宽度的新图像,而是根据原始图像的比例计算它们应该是什么,否则您的缩放图像会失真。例如,下面的代码将创建一个适当调整大小的图像,该图像将适合给定的矩形$w x $h
:
$tW = $width; //original width
$tH = $height; //original height
$w = postvar;
$h = postvar;
if($w == 0 || $h == 0) {
//error...
exit;
}
if($tW / $tH > $w / $h) {
// specified height is too big for the specified width
$h = $w * $tH / $tW;
}
elseif($tW / $tH < $w / $h) {
// specified width is too big for the specified height
$w = $h * $tW / $tH;
}
$tn = imagecreatetruecolor($w, $h); //this will create it with black background
imagefill($tn, 0, 0, imagecolorallocate($tn, 255, 255, 255)); //fill it with white;
//now you can copy the original image:
$image = imagecreatefromjpeg('filepathhere.jpeg');
//next line will just create a scaled-down image
imagecopyresampled($tn, $image, 0, 0, 0, 0, $w, $h, $tW, $tH);
现在,如果您只想复制原始图像的某个部分,例如从坐标($x, $y)
到右上角,那么您需要将其包含在计算中:
$tW = $width - $x; //original width
$tH = $height - $y; //original height
$w = postvar;
$h = postvar;
if($w == 0 || $h == 0) {
//error...
exit;
}
if($tW / $tH > $w / $h) {
// specified height is too big for the specified width
$h = $w * $tH / $tW;
}
elseif($tW / $tH < $w / h) {
// specified width is too big for the specified height
$w = $h * $tW / $tH;
}
$tn = imagecreatetruecolor($w, $h); //this will create it with black background
imagefill($tn, 0, 0, imagecolorallocate($tn, 255, 255, 255)); //fill it with white;
//now you can copy the original image:
$image = imagecreatefromjpeg('filepathhere.jpeg');
//next line will create a scaled-down portion of the original image from coordinates ($x, $y) to the lower-right corner
imagecopyresampled($tn, $image, 0, 0, $x, $y, $w, $h, $tW, $tH);
如果您提供有关您要实现的目标的更多详细信息,我可能会提供进一步的帮助。