python利用PIL将无损png转换成有损的jpg大大减小占用内存

该博客介绍了如何利用Python和OpenCV库将无损PNG图片批量转换为有损的JPG格式,从而减少内存占用。通过调整图片大小和设置高质量保存参数,实现了图片的高效压缩。代码示例展示了针对单张图片的转换方法,并提供了批处理整个目录下PNG图片的实现。
摘要由CSDN通过智能技术生成

利用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))
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值