利用python批量处理文件,将无损png转换成有损的jpg大大减小占用内存,这里调用了opencv的库。
png通常一个像素点是32位 r, g, b, a ,a表示透明度,而jpg的像素点是24位,r,g,b。将png转换成jpg的代码如下,利用如下代码将png转为jpg(并压缩)
一些参数:
Image.ANTIALIAS 表示压缩时一种高级伸缩的方法
from PIL import Image
import cv2 as cv
import os
### 用opencv实现png无损压缩到jpg压缩的方法 针对单张图片
def PNG_JPG(PngPath,SavePath):
img = cv.imread(PngPath, 0)
w, h = img.shape[::-1]
infile = PngPath
outfile = SavePath+PngPath.split("/")[-1].split(".")[0] + ".jpg"
print(outfile)
img = Image.open(infile)
#TODO 这里是将图片resize了,如果不需要将此代码删掉
img = img.resize((int(w / 2), int(h / 2)), 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=100)
# os.remove(PngPath)
else:
img.convert('RGB').save(outfile, quality=100)
# os.remove(PngPath)
return outfile
except Exception as e:
print("PNG转换JPG 错误", e)
# 批处理数据
path_root = os.getcwd()
Path='./images_withoutrect/'
img_dir = os.listdir(Path)
count=0
for img in img_dir:
if img.endswith('.png'):
PngPath= Path + img
PNG_JPG(PngPath,"./images_jpg/")
count+=1
print("中转换了{}张图".format(count))