python批量压缩图片

Python批量压缩图片

需求

每月拍摄不少照片,需要批量将图片在word中排版,但直接排版,生成的word会很大,需要提前将图片压缩。现编写2个程序,一个实现图片批量压缩,一个实现批量在word排版。。

压缩图片

参考教程
文中使用CV进行压缩,需提前安装OPENCV

pip install opencv-python

具体代码

  
  
import cv2  
import os  
import numpy as np  
from PIL import Image  
  
  
def pic_compress_png(image_path,new_image_path):  
    '''  
    将图片压缩成png格式  
    :param image_path:  原始文件路径  
    :param new_image_path:  保存文件路径  
    :return:    '''    files = os.listdir(image_path)  # 获取当前路径下的所有文件名字  
    files = np.sort(files)         #按名称排序  
    i = 0  
    for f in files:  
        imgpath = image_path + f   #路径+文件名字  
        img = cv2.imread(imgpath, 1)   #读取图片  
        heigh, width = img.shape[:2]  
        dirpath = new_image_path       #压缩后存储路径  
        file_name, file_extend = os.path.splitext(f)   #将文件名的,名字和后缀进行分割  
        dst = os.path.join(os.path.abspath(dirpath), file_name + '.png')  #文件最终保存的路径及名字(名字和压缩前的名字一致),  
        print(os.path.join(dirpath,"1.png"))  #打印压缩缓存文件路径  
        shrink = cv2.resize(img, (int(heigh*compress_rate), int(width*compress_rate)),  
                                interpolation=cv2.INTER_AREA) #对图像的大小进行resize   4864 *1024  
        cv2.imwrite(os.path.join(dirpath,"1.png"), shrink, [cv2.IMWRITE_PNG_COMPRESSION, 1]) #对图像进行压缩 【cv2.IMWRITE_PNG_COMPRESSION, 1】  
                                                                                            #v2.IMWRITE_PNG_COMPRESSION  压缩品质 0-10 ,数字越小压缩比越小  
        img1 = Image.open(os.path.join(dirpath,"1.png"))    #打开压缩后的缓冲文件  
        img1.save(dst,quality=70)                          #二次压缩,并保存位原始文件的文件名  
        os.remove(os.path.join(dirpath,"1.png"))           #删除缓存文件  
  
  
  
# Press the green button in the gutter to run the script.  
if __name__ == '__main__':  
    image_path = './12/'  # 原始文件路径  
    new_image_path = './11-1/' # 压缩后文件保存路径  
    compress_rate = 0.2  
    pic_compress_png(image_path,new_image_path)  
    print("压缩完成")  
  

在调试过程中会出现# AttributeError: ‘NoneType‘ object has no attribute ‘shape‘
这是没有读取到图片信息,解决参考,存储路径和图片名称不能有汉字,需要两个双斜杠。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值