【问题标题】:Place an image to the center of another image using PHP GD使用 PHP GD 将图像放置到另一个图像的中心
【发布时间】:2016-10-06 13:42:59
【问题描述】:

我需要将一个图像放置到另一个尺寸为 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 也被删除。我在这做错了什么?

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

【问题讨论】:

  • “居中”是什么意思?图像周围有边距?还是没有左右边距,只有上下边距?您当前的示例将开始将图像从中间复制到角落。
  • 一个预期输出的例子会很好。
  • @Proger_Cbsk..图像周围应该有边距..生成的图像应该在水平和垂直方向的透明图像内居中。

标签: php image gd


【解决方案1】:

所以你需要这样的东西吗?

@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,你完全应该这样做。

【讨论】:

    猜你喜欢
    • 2011-09-02
    • 1970-01-01
    • 2010-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多