欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

批量将PNG转为JPG

发布时间:2025/5/22 编程问答 39 豆豆
生活随笔 收集整理的这篇文章主要介绍了 批量将PNG转为JPG 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

因为最近想把自己的“认知卡片”项目上云,受限于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_pathoutfile = 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 BMPr, 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 outfileexcept 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_filesif __name__ == '__main__':# 传入空的list接收文件名contents = show_files(r"C:\Users\CTH\Desktop\tmp", [])

参考:
https://www.cnblogs.com/jiyanjiao-702521/p/10442416.html
https://www.cnblogs.com/cnapple/p/11792577.html

总结

以上是生活随笔为你收集整理的批量将PNG转为JPG的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。