We often need to insert a large number of pictures in some files such as Word, Excel, PPT, etc., but the memory of each picture is not small, and if the accumulation is too large, the memory of the file is too large, causing customers to fail to open the file. Open the file, then we can compress the memory of the picture! !
I also found a lot of solutions, and finally solved it! Next, just follow the gourd painting! !
The first step is to prepare two folders
Folder 1 [Original Picture]
Folder 2 [after compression]
The second step, the library that needs to be installed
library | Install |
---|---|
PIL | pip install Pillow |
code:
compressImage(r".\Original image", r".\Compressed"), there are two parameters in total, one is the original file, and the other is to store the compressed image
from PIL import Image
import os
import os.path
def picIsCorrect(fileSuffix):
if fileSuffix == ".png" or fileSuffix == ".jpg" or fileSuffix == ".jpeg":
return True
else:
return False
def compressImage(srcPath, dstPath):
for filename in os.listdir(srcPath):
if not os.path.exists(dstPath):
os.makedirs(dstPath)
srcFile = os.path.join(srcPath, filename)
dstFile = os.path.join(dstPath, filename)
# print(srcFile)
# print(dstFile)
srcFiledirName = os.path.dirname(srcFile)
basename = os.path.basename(srcFile) # 获得文件全称 例如 migo.png
filename, fileSuffix = os.path.splitext(
basename) # 获得文件名称和后缀名 例如 migo 和 png
if os.path.isfile(srcFile) & picIsCorrect(fileSuffix):
try:
sImg = Image.open(srcFile).convert('RGB')
w, h = sImg.size
# print(w, h)
dImg = sImg.resize((int(w / 2), int(h / 2)), Image.ANTIALIAS)
dImg.convert('RGB').save(dstFile)
print(dstFile + "压缩完成!!")
except (IOError, ZeroDivisionError) as e:
print(e.message)
if os.path.isdir(srcFile):
compressImage(srcFile, dstFile)
if __name__ == '__main__':
compressImage(r".\png", r".\test")
Effect: