import numpy as np
from PIL import Image
import cv2 as cv
import os
# 压缩并替换文件夹下的所有图片
#遍历文件夹
def iter_files(rootDir):
#遍历根目录
for root,dirs,files in os.walk(rootDir):
for file in files:
file_name = os.path.join(root,file)
if(file_name.lower().endswith('.jpg')):
replace_jpg(file_name)
# print(file_name)
if(file_name.lower().endswith('.png')):
PNG2JPG(file_name)
#jpg压缩替换jpg
def replace_jpg(file_name):
# 如果是文件就处理
if os.path.isfile(file_name):
try:
# 打开原图片缩小后保存,可以用if srcFile.endswith(".jpg")或者split,splitext等函数等针对特定文件压缩
sImg = Image.open(file_name)
w, h = sImg.size
if (w > 3000 or h > 3000):
w, h = w / 2, h / 2
dImg = sImg.resize((int(w), int(h)), Image.ANTIALIAS) # 设置压缩尺寸和选项,注意尺寸要用括号
dImg.save(file_name) # 也可以用srcFile原路径保存,或者更改后缀保存,save这个函数后面可以加压缩编码选项JPEG之类的
print(file_name + " 成功!")
except Exception:
print(file_name + "失败!")
# PNG转JPG替换源文件 压缩
def PNG2JPG(PngPath):
# img = cv.imread(PngPath, 0)
img=cv.imdecode(np.fromfile(PngPath,dtype=np.uint8),0) # 解决中文路径错误
w, h = img.shape[::-1]
if (w > 3000 or h > 3000):
w, h = w / 2, h / 2
infile = PngPath
outfile = os.path.splitext(infile)[0] + ".jpg"
img = Image.open(infile)
img = img.resize((int(w), int(h)), Image.ANTIALIAS)
try:
if len(img.split()) == 4:
# prevent IOError: cannot write mode RGBA as BMP
r, g, b, a = img.split()
img = Image.merge("RGB", (r, g, b))
img.convert('RGB').save(outfile, quality=75)
os.remove(PngPath)
else:
img.convert('RGB').save(outfile, quality=75)
os.remove(PngPath)
print(outfile + " PNG转换JPG成功 ")
except Exception:
print('\033[1;31m %s \033[0m' % "PNG转换JPG 错误")
print("PNG转换JPG 错误")
if __name__ == '__main__':
iter_files(r"E:/")
python 批量压缩并替换原图片
最新推荐文章于 2024-04-17 15:15:00 发布