Pngquant-在mac上的使用

2019-09-29  本文已影响0人  放羊娃华振

Pngquant是一个十分有效的png图片压缩工具。相信很多伙伴都用过tinypng这个网站去压缩图片,但是这个服务是有数量的限制的。我们这里就在mac电脑上实现一个类似tinypng的服务。
一、体验tinypng:
体验地址:https://tinypng.com/
二、自己在mac上实现图片压缩
1、下载pngquant:
地址:https://pngquant.org/
2、解压下载后的zip文件:

image.png
3、编写调用的代码。
代码一:pngquantWrapper
#!/bin/bash
if [ -z "$1" ]; then
        echo usage: compressimg [file]
        echo This tool will apply common image optimization techniques to the given file.
        exit
fi
OLDSIZE=`ls -l $1 | awk '{ print $5}'`

./pngquant --force --skip-if-larger $1 --output $1.tmp

if [ -f $1.tmp ]; then 
mv $1.tmp $1
fi 

NEWSIZE=`ls -l $1 | awk '{ print $5}'`

# show final stats
let RESULT=100-$NEWSIZE*100/$OLDSIZE
echo $1 $NEWSIZE'/'$OLDSIZE ' - ['$RESULT'% COMPRESSED]'

代码二:PNGCompress

#!/bin/bash
if [ -z "$1" ]; then
    echo usage: compressimg [directory or file]
    exit
fi

# apply the compressimg script to every image file within the given directory
# if the input is a single file, execute the script on it
OLDSIZE=`du -sk $1 | awk '{ print $1}'`
# echo 'OLDSIZE'
# echo $OLDSIZE
INPUTTYPE="Directory"

# execute compression
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
if [ -d $1 ]; then
    find $1 -type f \( -name "*.png" \) -exec $DIR/pngquantWrapper '{}' \;
else
    INPUTTYPE="File"
    $DIR/pngquantWrapper $1
fi

NEWSIZE=`du -sk $1 | awk '{ print $1}'`
let RESULT=100-$NEWSIZE*100/$OLDSIZE
echo ''
echo $1 Finished.
echo 'NEWSIZE/OLDSIZE' $NEWSIZE'/'$OLDSIZE 
echo 'TOTAL:'$RESULT'% COMPRESSED.'
echo ''

4、使用方式:

sh PNGCompress PNG图片目录的完整路径

6、运行结果:

...
/Users/dzh/Desktop/test_png/device-2019-08-19-200146.png 292770/292770  - [0% COMPRESSED]
’是目录‘

/Users/dzh/Desktop/test_png Finished.
NEWSIZE/OLDSIZE 1404/2060
TOTAL:32% COMPRESSED.

如上效果,可以看到压缩该图片可以减少32%的体积,是不是十分的优秀?

上一篇 下一篇

猜你喜欢

热点阅读