使用 PHP GD 将一张图片放在另一张图片的中央

Place an image to the center of another image using PHP GD

我需要将一个图像放置到另一个尺寸为 700*350 的图像(水平和垂直)的中心。我正在尝试使用以下代码。但是我得到的图像被拉伸了。

@header("Content-Type: image/png");
$imageURL = "flower.jpg";

// create a transparent background image for placing the $imageURL image
$imageResource  = imagecreatetruecolor(700, 350);
imagesavealpha($imageResource, true);

$transparentColor  = imagecolorallocatealpha($imageResource, 0, 0, 0, 127);
imagefill($imageResource, 0, 0, $transparentColor);
$backgroundImage = imagecreatefromjpeg($imageURL);
list($width, $height) = getimagesize($imageURL);
imagecopyresampled($imageResource, $backgroundImage, 350, 175, 0, 0, 700, 350, $width, $height);
imagepng($imageResource, "newimage.jpg");

这不是使图像居中,而且当我 运行 此代码时,文件 flower.jpg 也被删除。我在这方面做错了什么?

谁能帮我解决这个问题?提前致谢。

所以你需要这样的东西?

@header("Content-Type: image/png");
$imageURL = "flower.jpg";

// create a transparent background image for placing the $imageURL image
$imageResource  = imagecreatetruecolor(700, 350);
imagesavealpha($imageResource, true);

$transparentColor  = imagecolorallocatealpha($imageResource, 0, 0, 0, 127);
imagefill($imageResource, 0, 0, $transparentColor);
$backgroundImage = imagecreatefromjpeg($imageURL);
list($width, $height) = getimagesize($imageURL);

imagecopyresampled($imageResource, $backgroundImage, 175, 85, 0, 0, 350, 175, $width, $height);
imagepng($imageResource, "newimage.jpg");
imagedestroy($imageResource);
imagedestroy($backgroundImage);

您已将目标图像的中心指定为目标坐标和整个目标图像大小,而不是将源图像调整到的中心矩形所需的尺寸。

你也没有做 imagedestroy,你完全应该这样做。