使用 PHP 实现 GD 库中的 imagepng() 和透明度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1705098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:34:47  来源:igfitidea点击:

imagepng() and transparency in GD library with PHP

phpgd

提问by Strawberry

When using the function imagepng()in PHP, how can I make sure the images that I save are saved with a transparent background?

imagepng()在 PHP 中使用该函数时,如何确保我保存的图像以透明背景保存?

采纳答案by Eric

Here is an example of the imagecolortransparentfunction (if it helps):

这是该imagecolortransparent功能的示例(如果有帮助):

<?php
// Create a 55x30 image
$im = imagecreatetruecolor(55, 30);
$red = imagecolorallocate($im, 255, 0, 0);
$black = imagecolorallocate($im, 0, 0, 0);

// Make the background transparent
imagecolortransparent($im, $black);

// Draw a red rectangle
imagefilledrectangle($im, 4, 4, 50, 25, $red);

// Save the image
imagepng($im, './imagecolortransparent.png');
imagedestroy($im);
?>

回答by mauris

Simply do this:

只需这样做:

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

Before outputting. Make sure that all source files (if you used any) are set to PNG 32-bit with transparency - if not the output may differ with black background or transparency does not comply.

输出前。确保所有源文件(如果您使用过)都设置为具有透明度的 PNG 32 位 - 如果不是,则输出可能与黑色背景不同或透明度不符合要求。

回答by user2731504

Here is the example

这是例子

     $newimage = imagecreatetruecolor($dst_w, $dst_h);
     imagealphablending($newimage, false);
     imagesavealpha($newimage, true);
     $transparentindex = imagecolorallocatealpha($newimage, 255, 255, 255, 127);
     imagefill($newimage, 0, 0, $transparentindex);

回答by lamelas

There's a function called imagecolortransparentthat allows you to set which color is made transparent. I don't know if this answers your question.

有一个名为imagecolortransparent的函数,它允许您设置透明的颜色。我不知道这是否回答了你的问题。