问题描述
我一直在寻找调整png大小时如何正确管理alpha的方法.我设法使其保持透明,但仅适用于完全透明的像素.这是我的代码:
I have looked all over for how to correctly manage alpha when I'm resizing a png. I've managed to get it to keep transparency, but only for pixels that are completely transparent. Here's my code:
$src_image = imagecreatefrompng($file_dir.$this->file_name);
$dst_image = imagecreatetruecolor($this->new_image_width, $this->new_image_height);
imagealphablending($dst_image, true);
imagesavealpha($dst_image, true);
$black = imagecolorallocate($dst_image, 0, 0, 0);
imagecolortransparent($dst_image, $black);
imagecopyresampled($dst_image, $src_image, 0, 0, 0, 0, $this->new_image_width,
$this->new_image_height, $this->image_width, $this->image_height);
imagepng($dst_image, $file_dir.$this->file_name);
从此源图像开始:
调整大小后的图像如下:
The resized image looks like this:
我查看过的有关此问题的几乎所有论坛帖子的解决方案都说要执行以下操作:
The solution for almost every forum post I've looked at about this issue say to do something like this:
imagealphablending($dst_image, false);
$transparent = imagecolorallocatealpha($dst_image, 0, 0, 0, 127);
imagefill($dst_image, 0, 0, $transparent);
此代码的结果无法保存任何Alpha:
The results from this code fails at saving any alpha whatsoever:
还有其他解决方案吗?我是否缺少Alpha混合功能?为什么对其他所有人都有效,却对我却完全失败?我正在使用MAMP 2.1.3和PHP 5.3.15.
Is there any other solution? Am I missing something with the alpha blending? Why would that work for everyone else, yet utterly fail for me? I'm using MAMP 2.1.3 and PHP 5.3.15.
推荐答案
"They have not worked at all and I'm not sure why."
好吧,你一定做错了什么.链接重复副本中的代码,并添加了几行来加载和保存图像:
Well you must have been doing something wrong. The code from the linked duplicate with a couple of lines added to load and save the image:
$im = imagecreatefrompng(PATH_TO_ROOT."var/tmp/7Nsft.png");
$srcWidth = imagesx($im);
$srcHeight = imagesy($im);
$nWidth = intval($srcWidth / 4);
$nHeight = intval($srcHeight /4);
$newImg = imagecreatetruecolor($nWidth, $nHeight);
imagealphablending($newImg, false);
imagesavealpha($newImg,true);
$transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);
imagefilledrectangle($newImg, 0, 0, $nWidth, $nHeight, $transparent);
imagecopyresampled($newImg, $im, 0, 0, 0, 0, $nWidth, $nHeight,
$srcWidth, $srcHeight);
imagepng($newImg, PATH_TO_ROOT."var/tmp/newTest.png");
产生图像:
即这个问题(和答案)是完全重复的.
i.e. this question (and answer) are a complete duplicate.
这篇关于在php中使用透明性调整图像大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!