简体   繁体   中英

imagepng() and transparency in GD library with PHP

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

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.

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);

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

<?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);
?>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM