PHP gdLib 8-Bit PNG with alpha

元气小坏坏 提交于 2019-12-08 17:07:37

问题


how is it possible to save my image, created with gd, as an png-8?

it saves as gif with transparent channel well - but I want to use png-8.

Best Regards, Beerweasle


回答1:


Using imagesavealpha() and a transparent bg color should do the trick...

Based on dfilkovi's code:

<?php
// Create a new true color image
$im = new imagecreatetruecolor(100, 100);

// Fill with alpha background
$alphabg = imagecolorallocatealpha($im, 0, 0, 0, 127);
imagefill($im, 0, 0, $alphabg);

// Convert to palette-based with no dithering and 255 colors with alpha
imagetruecolortopalette($im, false, 255);
imagesavealpha($im, true);

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



回答2:


@Sonny

false assumption: PNG of any bit depth can have transparency. It is recorded in the tRNS chunk of the png image (except for truecolor ones) cf format definition

cf www.libpng.org/pub/png/spec/1.2/PNG-Chunks.html#C.tRNS

idem www.w3.org/TR/PNG-Chunks.html#C.tRNS

The difference is how it is recorder: RGBA has a unique record per pixel, with 4 values (3 colors and 1 alpha channel), where "paletted" PNG records alpha channel in its own chunk.

Fireworks is very good at it.

Examples:

http://www.libpng.org/pub/png/pngs-img.html




回答3:


I had to add the line imagecolortransparent($im, $alphabg); to the following code (taken from previous answer) for this to work:

// Fill with alpha background
$alphabg = imagecolorallocatealpha($im, 0, 0, 0, 127);
imagecolortransparent($im, $alphabg);
imagefill($im, 0, 0, $alphabg);

// Convert to palette-based with no dithering and 255 colors with alpha
imagetruecolortopalette($im, false, 255);
imagesavealpha($im, true);

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



回答4:


I think this could help you.

http://roseindia.net/tutorial/php/phpgd/About-transparent.html




回答5:


<?php
// Create a new true color image
$im = new imagecreatetruecolor(100, 100);

// Convert to palette-based with no dithering and 255 colors
imagetruecolortopalette($im, false, 255);

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

this should make 8bit png




回答6:


Building on dfilkovi's solution, have you tried using imagesavealpha() to save the full alpha channel information?



来源:https://stackoverflow.com/questions/1761986/php-gdlib-8-bit-png-with-alpha

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!