png图片压缩工具pngquant

来源:互联网 发布:建筑三维制图软件 编辑:程序博客网 时间:2024/05/28 17:05

近期项目有个需求,将上传的png图片做压缩处理,节省空间及提升网站性能,刚开始的时候了解过imagemagick,但imagemagick在png图片压缩方面感觉不尽人意,有时候压缩后比压缩前还要大,所以需要寻求其它方案解决png压缩的问题。

经过了解,找到了tinypng,在上面测试了下,png的压缩的确能够达到很好的效果,大小能够减少70%左右而且并不失真,本想着终于找到解决的方法了,但再经过了解得知,tinypng需要收费,不收费每天500张上限,而且调用它的api做压缩处理,如此一来,不想花钱又想完成任务恐怕是不可能了,而且调用第三方api总要连接人家服务器做处理,性能肯定不行。

抱着再找找的态度,竟然找到了pngquant,pngquant是开源的png压缩工具,可以直接安装到linux服务器上面,而且官方上面还声明它与tinypng有千丝万缕的关系,测试过后感觉很不错,那就用它了。

首先就要到官网去下载:

[root@bush src]# wget http://pngquant.org/pngquant-2.9.0-src.tar.gz


到目前为止,这个包是最新的,想要了解更多请到官网:http://pngquant.org


下载回来后解压:

[root@bush src]# tar -zxvf pngquant-2.9.0-src.tar.gz


进入解压后的文件夹,并设置安装路径进行安装:


[root@bush pngquant-2.9.0]# ./configure --prefix=/usr/local... ...[root@bush pngquant-2.9.0]# make install... ...[root@bush pngquant-2.9.0]# make clean... ...

安装成功后就可以直接在php里面使用了,官方有php开发文档,下面是针对我自己项目的一个方法:

/**--------------------------------------------------------------------- * @param $path_to_png_file * @param int $max_quality * @return bool|int|void */public function pngquant_compress($path_to_png_file, $max_quality = 90){    if (!file_exists($path_to_png_file)) {        $this->set_error("File does not exist: ".$path_to_png_file);        return false;    }    // guarantee that quality won't be worse than that.    $min_quality = 80;    // '-' makes it use stdout, required to save to $compressed_png_content variable    // '<' makes it read from the given file path    // escapeshellarg() makes this safe to use with any path    $compressed_png_content = shell_exec($this->lib_png_compress." --quality=$min_quality-$max_quality - < ".escapeshellarg($path_to_png_file));    if (!$compressed_png_content) {        $this->set_error('Conversion to compressed PNG failed. Is pngquant 1.8+ installed on the server?');        return false;    }    return @file_put_contents($path_to_png_file, $compressed_png_content);}

针对上面的思路做相应的程序封装,就可以运用到项目当中,图片的处理依然保留imagemagick的处理或者gd2。除了png,需要时都使用imagemagick压缩,png则单独使用pngquant处理。


0 0