CodeIgniter中PNG图片处理背景不透明问题的解决办法

BS一下自己起的这个标题。

本文仅限于解决使用GD2来处理图片的情况。

我想很多用CodeIgniter的人都会有这样的需求,用户上传了一张照片,需要对照片进行一定的修改以后(缩放,调整大小)再存储下来,但是如果用户上传了一张背景透明的PNG图片,那么我们使用CodeIgniter中的Image_lib进行裁剪以后,将会得到一张背景是黑色的图片,为什么会产生这个错误呢,我们来看一下CI的处理逻辑。

  1. 新建一张图片,该图片默认是黑色不透明背景
  2. 把源图片相应区域中的内容复制到新图片上
  3. 处理完毕

毫无疑问,你将获得一张黑色背景的图片,其最根本原因还是在于使用GD2来处理图片时,imagecreatetruecolor函数本身生成的就是一张黑色不透明的图片,你把一个透明的图片拷贝到它上面,当然背景就变黑了,所以我们只要在以上步骤里的1与2之间添加处理,将新图片的背景设置成100%透明即可以解决这个问题。

在Image_lib.php(CodeIgniter 1.71版本)的515行

即$dst_img = $create($this->width, $this->height);之后添加

// Transparent the background!!!
if ($create == ‘imagecreatetruecolor’)
{
imagesavealpha($dst_img, true);

$color = imagecolorallocatealpha($dst_img, 0, 0, 0, 127);
imagefill($dst_img, 0, 0, $color);
}

便可以解决问题了。

更新,提供另一种办法:

// Transparent the background!!!
if ($create == ‘imagecreatetruecolor’)
{
imagealphablending($dst_img, false);
imagesavealpha($dst_img, true);
}

<!– end –>

2009年9月17日 | 归档于 CodeIgniter
标签: ,
本文目前尚无任何评论.

发表评论

XHTML: 您可以使用这些标签: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">