簡體   English   中英

GD:將PNG的白色背景設為透明

[英]GD: Making white background for PNG transparent

我有一個透明背景的PNG水印圖像。 但是隨機會產生白色背景,而不是保持透明。

// Watermark
$watermark = imagecreatefrompng($docRoot . '/images/misc/watermark.png');
list($mwidth, $mheight) = getimagesize($docRoot . '/images/misc/watermark.png');

// Combinde watermark image with image already generated in $dst
imagecopy($dst, $watermark, $tnWidth-$mwidth-5, $tnHeight-$mheight-5, 0, 0, $mwidth, $mheight);

解決方法是添加:

imagealphablending($dst, true);
imagesavealpha($dst, true);

完整的代碼:

// Watermark
$watermark = imagecreatefrompng($docRoot . '/images/misc/watermark.png');
list($mwidth, $mheight) = getimagesize($docRoot . '/images/misc/watermark.png');

imagealphablending($dst, true);
imagesavealpha($dst, true);

// Combinde watermark image with image already generated in $dst
imagecopy($dst, $watermark, $tnWidth-$mwidth-5, $tnHeight-$mheight-5, 0, 0, $mwidth,

嘗試使用imagecopymerge而不是imagecopy

編輯:嘗試此代碼:

header('Content-type: image/jpeg');
$dst = imagecreatefromjpeg($image_path);
$watermark = imagecreatefrompng($docRoot . '/images/misc/watermark.png');
list($mwidth, $mheight) = getimagesize($docRoot . '/images/misc/watermark.png');
imagecopymerge($dst, $watermark, $tnWidth-$mwidth-5, $tnHeight-$mheight-5, 0, 0, $mwidth, $mheight, 100);
imagejpeg($dst,'',90);
imagedestroy($dst);

使用alpha通道保存$dst ,而不是$watermark

// Watermark
$watermark = imagecreatefrompng($docRoot . '/images/misc/watermark.png');
list($mwidth, $mheight) = getimagesize($docRoot . '/images/misc/watermark.png');

imagealphablending($dst, false);
imagesavealpha($dst, true);

// Combinde watermark image with image already generated in $dst
imagecopy($dst, $watermark, $tnWidth-$mwidth-5, $tnHeight-$mheight-5, 0, 0, $mwidth, $mheight);

我遇到了同樣的問題,但為了使其正常工作,我從代碼中注釋了這兩行:

imagesavealpha($image_1, true);
imagesavealpha($image_2, true);

所以我的代碼看起來像這樣:

$image_1 = imagecreatefrompng("example26_".$acct.".png");
$image_2 = imagecreatefrompng('example27.png');
imagealphablending($image_1, true);
imagealphablending($image_2, true);
//imagesavealpha($image_1, true);
//imagesavealpha($image_2, true);
imagecopy($image_1, $image_2, 0, 0, 0, 0, 1350, 250);
header("Content-Type: image/png");
imagepng($image_1);

現在,兩張圖片合並並保留了透明度,並使用這兩行生成了隨機的白色背景,希望這對其他遇到相同問題的人有所幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM