GD and Image 函数
在线手册:中文 英文
PHP手册

imagesavealpha

(PHP 4 >= 4.3.2, PHP 5)

imagesavealpha设置标记以在保存 PNG 图像时保存完整的 alpha 通道信息(与单一透明色相反)

说明

bool imagesavealpha ( resource $image , bool $saveflag )

imagesavealpha() 设置标记以在保存 PNG 图像时保存完整的 alpha 通道信息(与单一透明色相反)。

要使用本函数,必须将 alphablending 清位(imagealphablending($im, false))。

不是所有的浏览器都支持 alpha 通道,如果在你的浏览器上碰到问题,试着用兼容 alpha 通道的浏览器(例如最新版的 Mozilla)重新加载脚本。

Note: 此函数需要 GD 2.0.1 或更高版本(推荐 2.0.28 及更高版本)。

参见 imagealphablending()

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的图象资源。

saveflag

Whether to save the alpha channel or not. Default to FALSE.

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE.

范例

Example #1 imagesavealpha() example

<?php
// Load a png image with alpha channels
$png imagecreatefrompng('./alphachannel_example.png');

// Do required operations

// Turn off alpha blending and set alpha flag
imagealphablending($pngfalse);
imagesavealpha($pngtrue);

// Output image to browser
header('Content-Type: image/png');

imagepng($png);
imagedestroy($png);
?>

注释

Note: 此函数需要 GD 2.0.1 或更高版本(推荐 2.0.28 及更高版本)。

参见


GD and Image 函数
在线手册:中文 英文
PHP手册
PHP手册 - N: 设置标记以在保存 PNG 图像时保存完整的 alpha 通道信息(与单一透明色相反)

用户评论:

ray hatfield (23-Feb-2011 07:01)

After much trial and error and gnashing of teeth I finally figured out how to composite a png with an 8-bit alpha onto a jpg. This was not obvious to me so I thought I'd share. Hope it helps.

I'm using this to create a framed thumbnail image:

<?php
// load the frame image (png with 8-bit transparency)
$frame = imagecreatefrompng('path/to/frame.png');

// load the thumbnail image
$thumb = imagecreatefromjpeg('path/to/thumbnail.jpg');

// get the dimensions of the frame, which we'll also be using for the
// composited final image.
$width = imagesx( $frame );
$height = imagesy( $frame );

// create the destination/output image.
$img=imagecreatetruecolor( $width, $height );

// enable alpha blending on the destination image.
imagealphablending($img, true);

// Allocate a transparent color and fill the new image with it.
// Without this the image will have a black background instead of being transparent.
$transparent = imagecolorallocatealpha( $img, 0, 0, 0, 127 );
imagefill( $img, 0, 0, $transparent );

// copy the thumbnail into the output image.
imagecopyresampled($img,$thumb,32,30,0,0, 130, 100, imagesx( $thumb ), imagesy( $thumb ) );

// copy the frame into the output image (layered on top of the thumbnail)
imagecopyresampled($img,$frame,0,0,0,0, $width,$height,$width,$height);

imagealphablending($img, false);

// save the alpha
imagesavealpha($img,true);

// emit the image
header('Content-type: image/png');
imagepng( $img );

// dispose
imagedestroy($img);

// done.
exit;
?>

tobias at silverxnet dot de (07-Dec-2009 02:07)

As I needed a function that enables me to put a separate mask into the alpha channel of a picture, I found there is no function to allow this directly via PHP/GD, hence I wrote a quick'n'dirty function that does the trick.

For the mask any format is fine (jpg, png, gif, ...). Black will be transparent, white will be opaque - greyscale makes it half transparent, like with any alpha channel. The alpha channel is only 7 bit, hence there are just 128 variations of transparency possible.

I use the red channel, for the transparency, so you can make it either greyscale or redscale, doesn't matter.

<?php
function imagealphamask( &$picture, $mask ) {
   
// Get sizes and set up new picture
   
$xSize = imagesx( $picture );
   
$ySize = imagesy( $picture );
   
$newPicture = imagecreatetruecolor( $xSize, $ySize );
   
imagesavealpha( $newPicture, true );
   
imagefill( $newPicture, 0, 0, imagecolorallocatealpha( $newPicture, 0, 0, 0, 127 ) );
   
   
// Resize mask if necessary
   
if( $xSize != imagesx( $mask ) || $ySize != imagesy( $mask ) ) {
       
$tempPic = imagecreatetruecolor( $xSize, $ySize );
       
imagecopyresampled( $tempPic, $mask, 0, 0, 0, 0, $xSize, $ySize, imagesx( $mask ), imagesy( $mask ) );
       
imagedestroy( $mask );
       
$mask = $tempPic;
    }

   
// Perform pixel-based alpha map application
   
for( $x = 0; $x < $xSize; $x++ ) {
        for(
$y = 0; $y < $ySize; $y++ ) {
           
$alpha = imagecolorsforindex( $mask, imagecolorat( $mask, $x, $y ) );
           
$alpha = 127 - floor( $alpha[ 'red' ] / 2 );
           
$color = imagecolorsforindex( $picture, imagecolorat( $picture, $x, $y ) );
           
imagesetpixel( $newPicture, $x, $y, imagecolorallocatealpha( $newPicture, $color[ 'red' ], $color[ 'green' ], $color[ 'blue' ], $alpha ) );
        }
    }
   
   
// Copy back to original picture
   
imagedestroy( $picture );
   
$picture = $newPicture;
}
?>

To use the function is rather simple:
<?php
// Load source and mask
$source = imagecreatefrompng( 'myPicture.png' );
$mask = imagecreatefrompng( 'myMask.png' );

// Apply mask to source
imagealphamask( $source, $mask );

// Output
header( "Content-type: image/png");
imagepng( $source );
?>

Hope it helps!

phil at unabacus dot net (23-Apr-2008 02:47)

The comment left by "doggz at mindless dot com" will cause a duplication in layering of the transparent image - AlphaImageLoader loads the image as if it were a floating layer on top of the <img> element - so your image will double up.. so don't go thinking something very strange is happening with your PHP it's the silly browser ;)

The easiest (although not the best) way to get around this is to use the CSS background property instead of an image src - because as of yet you can't change an image's src dynamically using currently supported CSS:

<div style="width:200px; height:200px; background: url(my-trans-image.php); *background:url(); *filter:progid:
DXImageTransform.Microsoft.AlphaImageLoader(src='my-trans-image.php', sizingMethod='scale');"></div>

The above (although not pretty) keeps the image loaded as a background for any good browser as they should ignore the starred (*) CSS items and should support Alpha PNGs natively. IE will listen to the starred items and blank out the background whilst applying it's AlphaLoader on top. Obviously you need to know the width and height of your image but you can get this using getimagesize() or just by hardcoding.

Downsides to know:

1. Unless the user has 'backgrounds enabled when printing' your image wont show up when the webpage is printed.

2. You can't stretch or shrink a background image - if you change the div's dimensions from that of the image you will stretch it in IE (due to the 'scale' property - which you can change for sake of standardness to 'crop') but you will crop it in any other browser.

3. Most browsers treat images and backgrounds differently, in load priority and in the way the user can interact with them.

Other Options:

Other methods resort to using JavaScript or Browser Detection on the Server Side.

doggz at mindless dot com (06-Oct-2003 05:50)

To use PNG-24 in IE 5.5+ try:
<img alt="Transparant PNG" src="myimage.gif" style="width: 200px; height: 200px; filter:progid:
DXImageTransform.Microsoft.AlphaImageLoader(src='myimage.png', sizingMethod='scale')" />

there is more info available at http://people.brandeis.edu/~peelle/png/