解决thinkphp裁剪png图片背景不透明的方法

700 阅读1分钟
原文链接: www.shuchengxian.com

在使用thinkphp对图片处理的时候,对于png图片的处理比如裁剪,缩略图,都会出现背景为白色,不是透明的情况。

这里只是使用了thinkphp3.2.3版本,默认GD库处理,其他的类库自行解决哦。


下面我们看,thinkphp裁剪png图片背景不透明的问题怎么解决?


其实,解决起来也是很简单的,只要将文件ThinkPHP/Library/Think/Image/Driver/GD.class.php修改其中的三个方法即可。

1、save()方法,第98行。

原代码:

$fun  =   'image'.$type;
$fun($this->img, $imgname);

修改为:

$fun  =   'image'.$type;
imagesavealpha($this->img, true);
$fun($this->img, $imgname);

2、crop()方法,第168行。

原代码:

$color = imagecolorallocate($img, 255, 255, 255);
imagefill($img, 0, 0, $color);

修改为:

$color = imagecolorallocatealpha($img, 0, 0, 0, 127);
imagefill($img, 0, 0, $color);
imagesavealpha($img, true);

3、thumb()方法,第266行。

原代码:

$color = imagecolorallocate($img, 255, 255, 255);

修改为:

$color = imagecolorallocatealpha($img, 0, 0, 0, 127);


通过修改上面三处方法,即可实现thinkphp裁剪png图片支持透明的效果了。