Batch compression of png method instances with Python (support for filtering individual files and folders)
- 2020-06-12 09:56:56
- OfStack
preface
This paper mainly introduces Python batch compression png related materials, to share for your reference and learning, the following words do not say much, let's have a look at the detailed introduction:
1. The demand
Why is there a need? The reason is that most of the game resources are png images, which need to be compressed. However, some images and images in folders, the art does not want to be compressed, such as 1 aperture with transparency or the main elements of the game. So I'm going to filter it. python was found to be a good language for this scenario. So I wrote python.
2. The source code
import os,sys
import os.path
rootdir=sys.path[0]
# Files that need to be filtered
notActionFile = ["choose_bg1.png"]
# Folders to filter
notActionPath = ["test"]
# Files that need to be deleted
needDeleteFile = ["s2.png"]
def file_extension(path):
return os.path.splitext(path)[1]
for parent,dirnames,filenames in os.walk(rootdir):
for filename in filenames:
fullPath = os.path.join(parent,filename)
# Delete the file
for deleteFile in needDeleteFile:
if filename == deleteFile:
os.remove(fullPath)
isFilter = False
# Filter file compression
for noActionName in notActionFile:
if noActionName == filename:
isFilter = True
# Filter folder compression
for onePath in notActionPath:
lastPath = fullPath.split('\\')[-2]
if lastPath == onePath:
isFilter = True
if file_extension(fullPath) == ".png" and isFilter == False:
#print "action"
os.system("pngquant -f --ext .png --quality 50-80 \"" + fullPath + "\"")
print fullPath
pngquant is used for compression.
Complete the project download address: http: / / xiazai ofstack. com / 201707 / yuanma/compressImage (ofstack. com). rar
To do this, copy the two files to the folder that you want to compress and then execute python main.py
conclusion