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

查看:65
本文介绍了使用PHP的GDlib imagecopy重新采样时,能否保留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 imagecopy重新采样时,能否保留PNG图像的透明度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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