How to Use pngquant to compress png images in Python,

Source: Internet
Author: User
Tags tinypng

How to Use pngquant to compress png images in Python,

When it comes to png Image Compression, many people may know the website TinyPNG. However, if the PS plug-in requires money (although cracked), the Developer API will be connected to his server. without mentioning the network transmission speed, the Key is also subject to monthly restrictions.

But it seems that tinyPNG uses the technology from pngquant, at least in the http://pngquant.org/, so it claims: TinyPNG and Kraken. io-on-line interfaces for pngquant. If this is the case, I would like to talk to TinyPNG. The latter is open-source, and even the GUI tools provided on the home page are open-source. In addition, the principles of TinyPNG on the home page do not mention pngquant at once.

I used the pngquant command line to run the example graph on the tinyPNG homepage. The compression ratio and display effect are similar.

Pngquant tools on the home page, Pngyu (http://nukesaq88.github.io/Pngyu/) is cross-platform and open source, I think it is quite easy to use, directly put the folder inside the drag can recursive processing, supports various forms of generation (renaming, overwriting, storage to other directories, etc.), compression ratio after compression, and preview.

However, I still want to be able to process it through scripts. On the one hand, it is more customizable, and on the other hand it is more convenient to integrate it into the entire automated process chain. So I tried to write something in python again. Who knows ......

Pngquant's command line method is a bit pitfall ...... The parameter descriptions in help are inconsistent with the actual results.

1. The -- force parameter is invalid. If the output file exists, an error is returned. Ignore this parameter and specify the overwriting parameter.
2. The -- skip-if-larger parameter is abnormal. Sometimes the generated file is small and will be dropped by the skip ......

But fortunately, the python method is good. Although the command line itself cannot handle these problems, python can be processed at the upper layer. below is the actual recursive processing of png scripts in a folder:

'''pngquant.pyuse pngquant to reduces png file sizeRuoqian, Chen<piao.polar@gmail.com> ----------2015/4/31. del option --quality=50-90, special pic need skip can config in lod ini  lod ini format:[PixelFormat]map_01.png=0  0 means skip in file----------2015/4/21. desDir can be the same to srcDir, or another dir2. lod ini config can be not exist----------2015/3/31create'''import osimport os.pathimport sysimport ConfigParserimport stringPngquantExe="pngquant"thisFilePath = sys.path[0];print "this py file in dir : " + thisFilePathprojectPath = thisFilePath + "/../CMWar_2dx/CMWar_2dx/";srcResDir = "Resources/";dstResDir = "Resources/";lodIniPath = projectPath + srcResDir + "ini/pic.ini"keepOrgPaths = [];if os.path.exists(lodIniPath):  config = ConfigParser.SafeConfigParser()  config.read(lodIniPath)  section = "PixelFormat";  options = config.options(section)  for option in options:    value = string.atoi(config.get(section, option))    if not value:      keepOrgPaths.append(option);print keepOrgPathssrcResPath = projectPath + srcResDir;pngCount = 0;transCount = 0;#pngquant --force --skip-if-larger --ext .png --quality 50-90 --speed 1for parent,dirnames,filenames in os.walk(srcResPath):  print "----- process Dir " + parent  dstDir = parent.replace(srcResDir, dstResDir)  if not os.path.exists(dstDir):    os.makedirs(dstDir)  for filename in filenames:    if os.path.splitext(filename)[1] == '.png':      pngCount += 1;      srcFilePath = os.path.join(parent, filename);      dstFilePath = os.path.join(dstDir, filename);      tmpFilePath = dstFilePath + ".tmp";      if filename in keepOrgPaths:        print "----- keep ----- " + filename;      else:#        print "----- process ----- " + filename;#        cmd = "\"" + PngquantExe + "\"" + " --force --speed=1 --quality=50-90 -v " + srcFilePath + " -o " + tmpFilePath;        cmd = "\"" + PngquantExe + "\"" + " --force --speed=1 " + srcFilePath + " -o " + tmpFilePath;#        print cmd;        os.system(cmd)        if os.path.exists(tmpFilePath):          sizeNew = os.path.getsize(tmpFilePath);          sizeOld = os.path.getsize(srcFilePath);          if sizeNew < sizeOld:            open(dstFilePath, "wb").write(open(tmpFilePath, "rb").read())            transCount += 1;          os.remove(tmpFilePath)      if not os.path.exists(dstFilePath):        open(dstFilePath, "wb").write(open(srcFilePath, "rb").read())print "Done. Trans Pngs: %d/%d" %(transCount, pngCount)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.