PHP 8.3.4 Released!

imagesavealpha

(PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8)

imagesavealphaСохранять ли полную информацию альфа-канала при сохранении изображений

Описание

imagesavealpha(GdImage $image, bool $enable): bool

imagesavealpha() устанавливает флаг, определяющий, будет ли сохраняться полная информация альфа-канала (в противовес одноцветной прозрачности) и сохраняет изображение. Поддерживается только для форматов изображений, которые содержат полную информацию об альфа-канале, т.е. PNG, WebP и AVIF.

Замечание: Функция imagesavealpha() имеет смысл только для изображений PNG, поскольку для WebP и AVIF всегда сохраняется полный альфа-канал. Не рекомендуется полагаться на это поведение, так как оно может измениться в будущем. Таким образом, функцию imagesavealpha() следует вызывать намеренно также для изображений WebP и AVIF.

Альфа-смешивание должно быть отключено (imagealphablending($im, false)), чтобы альфа-канал сохранялся в первую очередь.

Список параметров

image

Объект GdImage, который возвращает одна из функций, создающих изображения, например, imagecreatetruecolor().

enable

Требуется ли сохранять альфа канал или нет. По умолчанию false.

Возвращаемые значения

Возвращает true в случае успешного выполнения или false в случае ошибки.

Список изменений

Версия Описание
8.0.0 Параметр image теперь ожидает экземпляр класса GdImage; раньше параметр ждал корректный gd-ресурс (resource).

Примеры

Пример #1 Пример использования imagesavealpha()

<?php
// Загрузка png изображения с альфа каналом
$png = imagecreatefrompng('./alphachannel_example.png');

// Выключение альфа-смешения
imagealphablending($png, false);

// Какие-то операции

// Установка альфа-флага
imagesavealpha($png, true);

// Вывод изображения и очистка памяти
header('Content-Type: image/png');

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

Смотрите также

  • imagealphablending() - Задание режима сопряжения цветов для изображения
add a note

User Contributed Notes 2 notes

up
20
ray hatfield
13 years ago
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;
?>
up
-1
phil at unabacus dot net
15 years ago
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.
To Top