因为最近想把自己的“认知卡片”项目上云,受限于PNG文件尺寸和有限带宽的矛盾,于是需要将近千张PNG转为JPG,从而在基本维持分辨率和图像视觉质量的前提下,使得文件大小缩减为原图的大约13%。代码如下:
- """
- 先来说一下jpg图片和png图片的区别
- jpg格式:是有损图片压缩类型,可用最少的磁盘空间得到较好的图像质量
- png格式:不是压缩性,能保存透明等图
- 先安装opencv包:pip install opencv-contrib-python
- """
- from PIL import Image
- import cv2 as cv
- import os
-
-
- # PNG到JPG的转换函数
- def png2jpg(png_path):
- img = cv.imread(png_path, 0)
- w, h = img.shape[::-1]
- infile = png_path
- 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=90)
- os.remove(png_path)
- else:
- img.convert('RGB').save(outfile, quality=90)
- os.remove(png_path)
- return outfile
- except Exception as e:
- print("PNG转换JPG 错误", e)
-
-
- # 递归遍历PNG文件
- def show_files(path, all_files):
- # 首先遍历当前目录所有文件及文件夹
- file_list = os.listdir(path)
- # 准备循环判断每个元素是否是文件夹还是文件,是文件的话,把名称传入list,是文件夹的话,递归
- for file in file_list:
- # 利用os.path.join()方法取得路径全名,并存入cur_path变量,否则每次只能遍历一层目录
- cur_path = os.path.join(path, file)
- # 判断是否是文件夹
- if os.path.isdir(cur_path):
- show_files(cur_path, all_files)
- else:
- # print(cur_path)
- filename, ext = os.path.splitext(file)
- if ext == ".png":
- print("PNG:" + cur_path)
- png2jpg(cur_path)
- all_files.append(file)
-
- return all_files
-
-
- if __name__ == '__main__':
- # 传入空的list接收文件名
- contents = show_files(r"C:\Users\CTH\Desktop\tmp", [])
-