ここにはいくつかの問題があります。まず、指定した新しい高さと幅で新しい画像を作成するのではなく、元の画像の比率に基づいてそれらがどうあるべきかを計算する必要があります。そうしないと、拡大縮小された画像が歪んでしまいます。たとえば、次のコードは、次の長方形に収まる適切なサイズの画像を作成します$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);
あなたが達成しようとしていることについてもっと詳しく教えていただければ、私はさらに手助けできるかもしれません。