【问题标题】:PHP GD image merge changing my image to blackPHP GD图像合并将我的图像更改为黑色
【发布时间】:2014-08-27 06:30:18
【问题描述】:

我有一个非常令人沮丧的情况。我是第一次使用 PHP GD,这有点像过山车的关系。基本上,我正在尝试将 2 个图像,一个正方形(高度/宽度为 x)合并到一个矩形(宽度为 x,高度为 y)上。

正方形需要垂直居中。但这不是问题 - 我已经设法正确定位它。

发生的事情是,我的矩形是白色的。我的正方形有一个白色背景,所以当图像合并时,它应该看起来就像我在白色矩形背景上的资产。

当我合并图像时,GD 出于某种原因将我的背景白色矩形更改为黑色 - 因此您可以看到中间的白色方块,顶部和底部都有黑色“条”。有人可以帮忙吗?

代码是:

//create copy of original image to correct size
imagecopyresized($dst_image, $src_image, 0,0,0,0,$x_width,$x_height,$orig_img_x_width,$orig_img_x_height);
imagejpeg($dst_image, "resized_copy.jpg", 100);

$img = imagecreatetruecolor(1333, 2000);
$white = imagecolorallocate($img, 255, 255, 255);
imagefill ( $img, 0, 0, $white );
imagefilledrectangle($img,0,0,1333,2000, $white);
imagejpeg($img, "rectangle.jpg", 100);

        //merge images
        $dest2 = imagecreatefromjpeg("rectangle.jpg");
        $src2 = imagecreatefromjpeg('resized_copy.jpg');

        imagecopymerge($dest2, $src2, 0, 0, 0, -333.5, $x_width, $x_height, 100);
        imagejpeg($dest2, "final_image.jpg", 100);

我尝试使用 imagecopy 而不是 imagecopymerge,但得到了相同的结果。我确信有一个简单的解释,但我似乎无法通过 php 手册找到它。

【问题讨论】:

  • 根据我有限的经验,GDLib 不像 PhotoShop 之类的程序,您可以在其中将不同大小的图像叠加在一起,并且它们都保持它们的大小。 GDLib 获取可能为 100 像素 x 100 像素的图像 A,并允许您将其放在可能为 200 像素 x 200 像素的图像 B 上,但它只能在顶部放置 200 像素 x 200 像素,因此它会扩展图像 A 的边框(黑色) 以匹配下方较大的尺寸。
  • 好的,如果有的话,你会推荐什么来实现这个过程?
  • 老实说,我不记得了,但我弄乱了所有的 alpha 通道函数来尝试分配黑色区域的透明度。

标签: php image gd


【解决方案1】:

我已多次阅读您的问题,但我不相信我完全理解您想要实现的目标,因此我在生成以下代码时做了一些假设。

为简单起见,我创建了一个“square.jpg”测试图像文件,如下所示:

(请注意,我在这里使用了小尺寸的图像,因此我可以内联显示它们。)

// read in the square test image.
$square    = imagecreatefromjpeg('square.jpg');
$square_x  = imagesx($square); // 100px
$square_y  = imagesy($square); // 100px
// create the rectangular image to merge with.
$rectangle = imagecreatetruecolor(100, 200);
$rectangle_x = imagesx($rectangle); // 100px
$rectangle_y = imagesy($rectangle); // 200px
// note that this isn't white, but rather a lovely shade of blue to better
// show the image on the white SO background!
$white = imagecolorallocate($rectangle, 128, 128, 255);
imagefill($rectangle, 0, 0, $white);
// merge the images.
imagecopymerge(
    $rectangle,
    $square,
    0,
    ($rectangle_y / 2) - ($square_y / 2), // to vertically centre the square.
    0,
    0,
    $square_x,
    $square_y,
    75 // Just to show the merge clearly; change back to 100 for your usage.
);

imagejpeg($rectangle, 'final_image.jpg', 100);

imagedestroy($rectangle);
imagedestroy($square);

这给了我final_image.jpg 中的以下图片:

【讨论】:

  • 工作就像一个魅力 - 不太确定为什么我的代码不起作用 - 认为我正在从第一个图像创建第二个图像 - 但代码很棒。谢谢。
猜你喜欢
  • 2011-02-11
  • 1970-01-01
  • 1970-01-01
  • 2011-04-25
  • 1970-01-01
  • 2011-09-28
  • 1970-01-01
  • 1970-01-01
  • 2013-03-17
相关资源
最近更新 更多