PHP + GD:imagecopymerge不保留PNG透明胶片 [英] PHP+GD: imagecopymerge not retaining PNG transparencies
问题描述
我有两个PNG文件:"red.png"和"blue.png";它们大部分都是透明的,但是在不同的地方都有一些红色或蓝色斑点.
I have two PNG files, "red.png" and "blue.png"; they are both mostly transparent, but there is a few pixels of red or blue splotches in various places.
我想制作一个将两者合并的PHP脚本;它应该像这样简单:
I want to make a PHP script that merges the two; it should be as simple as something like:
$original = getPNG('red.png');
$overlay = getPNG('blue.png');
imagecopymerge($original, $overlay, 0,0, 0,0, imagesx($original), imagesy($original), 100);
header('Content-Type: image/png');
imagepng($original);
当我运行此脚本时,我得到的只是蓝色的点-失去了透明度.我看到我应该添加以下内容:
When I run this script, all I get is the blue dots -- with the transparency lost. I saw that I should add these:
imagealphablending($original, false);
imagesavealpha($original, true);
(在原始图和覆盖图上?)这似乎无济于事.
(on both the original and the overlay?) And that doesn't seem to help any.
我在PHP.net上看到了一些变通方法,可以说是这样:
I saw a few workarounds on PHP.net, something to the tune of:
$throwAway = imagecreatefrompng($filename);
imagealphablending($throwAway, false);
imagesavealpha($throwAway, true);
$dstImage = imagecreatetruecolor(imagesx($throwAway), imagesy($throwAway));
imagecopyresampled($dstImage, $throwAway,0,0,0,0, imagesx($throwAway), imagesy($throwAway), imagesx($throwAway), imagesy($throwAway));
,应将PNG转换为真彩色"图像并保持透明度.似乎确实是这样做的,但是现在我所看到的只是黑色背景上的蓝色.
, which should convert the PNG to a "truecolor" image and retain transparency. It does seem to do so, but now all I see is blue on a black background.
我该怎么办?!
推荐答案
这对我来说非常合适:
$img1 = imagecreatefrompng('red.png');
$img2 = imagecreatefrompng('blue.png');
$x1 = imagesx($img1);
$y1 = imagesy($img1);
$x2 = imagesx($img2);
$y2 = imagesy($img2);
imagecopyresampled(
$img1, $img2,
0, 0, 0, 0,
$x1, $y1,
$x2, $y2);
imagepng($img1, 'merged.png', 0);
PHP版本5.3.2
GD 2.0版
libPNG版本1.2.42
PHP Version 5.3.2
GD Version 2.0
libPNG Version 1.2.42
您是否尝试过将图像保存到文件并进行检查?
Have you tried saving the image to a file and checking that?
这篇关于PHP + GD:imagecopymerge不保留PNG透明胶片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!