使用 PHP 的 GDlib imagecopyresampled 时能否保留 PNG 图像透明度? [英] Can PNG image transparency be preserved when using PHP's GDlib imagecopyresampled?

查看:22
本文介绍了使用 PHP 的 GDlib imagecopyresampled 时能否保留 PNG 图像透明度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下 PHP 代码片段使用 GD 将浏览器上传的 PNG 大小调整为 128x128.它工作得很好,除了原始图像中的透明区域在我的情况下被替换为纯色 - 黑色.

The following PHP code snippet uses GD to resize a browser-uploaded PNG to 128x128. It works great, except that the transparent areas in the original image are being replaced with a solid color- black in my case.

即使设置了 imagesavealpha,还是有些不对劲.

Even though imagesavealpha is set, something isn't quite right.

在重新采样的图像中保留透明度的最佳方法是什么?

What's the best way to preserve the transparency in the resampled image?

$uploadTempFile = $myField[ 'tmp_name' ]
list( $uploadWidth, $uploadHeight, $uploadType ) 
  = getimagesize( $uploadTempFile );

$srcImage = imagecreatefrompng( $uploadTempFile );    
imagesavealpha( $targetImage, true );

$targetImage = imagecreatetruecolor( 128, 128 );
imagecopyresampled( $targetImage, $srcImage, 
                    0, 0, 
                    0, 0, 
                    128, 128, 
                    $uploadWidth, $uploadHeight );

imagepng(  $targetImage, 'out.png', 9 );

推荐答案

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

为我做的.谢谢ceejayoz.

did it for me. Thanks ceejayoz.

注意,目标图像需要 alpha 设置,而不是源图像.

note, the target image needs the alpha settings, not the source image.

完整的替换代码.另请参阅下面的答案及其评论.这不保证在任何方面都是完美的,但确实满足了我当时的需求.

full replacement code. See also answers below and their comments. This is not guaranteed to be be perfect in any way, but did achieve my needs at the time.

$uploadTempFile = $myField[ 'tmp_name' ]
list( $uploadWidth, $uploadHeight, $uploadType ) 
  = getimagesize( $uploadTempFile );

$srcImage = imagecreatefrompng( $uploadTempFile ); 

$targetImage = imagecreatetruecolor( 128, 128 );   
imagealphablending( $targetImage, false );
imagesavealpha( $targetImage, true );

imagecopyresampled( $targetImage, $srcImage, 
                    0, 0, 
                    0, 0, 
                    128, 128, 
                    $uploadWidth, $uploadHeight );

imagepng(  $targetImage, 'out.png', 9 );

这篇关于使用 PHP 的 GDlib imagecopyresampled 时能否保留 PNG 图像透明度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆