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

即使设定了imagesavealpha,还是有些地方不太对劲.

在重采样的图像中保持透明度的最佳方式是什么?

$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.

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

编辑: 完全替换代码.另请参阅下面的答案和他们的 comments .这不能保证在任何方面都是完美的,但确实满足了我当时的需求.

$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相关问答推荐

如何使用Ubuntu在同一台服务器上为多个版本构建相同的php扩展?

PHP:从数组中获取唯一的数字组合

在WooCommerce管理订单页面中显示区域名称

照明\Support\Collection::Filter():参数#1($Callback)的类型必须为?可调用、已给定数组、已调用

Symfony装置加载:try 从命名空间加载类";ClassUtils";Doctrine\Common\Util";

从WC会话变量更改WooCommerce checkout 托运方法成本

根据产品类型显示或隐藏WooCommerce管理产品自定义字段

在Laravel中为表添加前缀,以将它们逻辑地分组

如何在PHP中出现弃用警告时触发错误?

有没有可能从composer 过时的输出中隐藏不需要的主要版本?

如何在UML类图中可视化变量引用数组

WooCommerce中特定付款方式的变更订单预留库存时间

打折时更改 Woocommerce 产品名称

将一个表中的行连接为不同表MYSQL中的一列

.htaccess 重写规则问题

自定义主键值未正确显示

如何在构建 PHP 类别数组树的递归函数中将父面包屑传递给子项?

如何从 PHP 中的 .txt 文件中列出今天生日的人的姓名?

如何在光速网络服务器中使用 apache ..htaccess

如何从 PHP 中的字符串位置排除图像扩展名