• python实现图片压缩和word排版


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

    压缩图片

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

    pip install opencv-python
    
    • 1

    具体代码为

      
      
    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("压缩完成")  
      
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43

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

    word中图片排版

    主要代码

    # -*- coding:utf-8 -*-  
    # @Time   : 2023-11-08  
    # @Author : Carl_DJ  
      
    '''  
    实现功能:  
       图片自动插入Word文档,  
       每行插入4张图片  
    '''  
    from docx import Document  
    from PIL import Image  
    import io  
    from docx import Document  
    from docx.shared import Inches  
    from PIL import Image  
    import os  
    import random  
    from docx.enum.section import WD_ORIENT  
    from docx.oxml.ns import qn  
      
    # 创建一个新的Word文档  
    doc = Document()  
      
    # 获取图像目录中的所有文件名  
    image_dir = "./12"  
    images = [f for f in os.listdir(image_dir) if os.path.isfile(os.path.join(image_dir, f))]  
      
    # 分成3栏  
    section = doc.add_section() # 添加横向页的连续节  
    section._sectPr.xpath('./w:cols')[0].set(qn('w:num'),'3')  
      
      
    # 将每个图像插入到文档中  
    row_num = 0  
    col_num = 0  
    for i, image_name in enumerate(images):  
        # 打开图像  
        img = Image.open(os.path.join(image_dir, image_name))  
      
        # 将图像转换为BytesIO对象  
        byte_arr = io.BytesIO()  
        img.save(byte_arr, format='PNG')  
        byte_arr.seek(0)  
        inline_shape = doc.add_picture(byte_arr, width=Inches(2), height=Inches(2))  
        # 插入图像  
      
        # 如果当前行已经满了(即插入了4张图片),则开始新的一行  
        # if col_num == 4:  
        #     row_num += 1    #     col_num = 0  
    # 保存文档  
    doc.save('output.docx')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
  • 相关阅读:
    ES集群搭建及Kibana安装
    蓝桥杯国赛算法复习
    Jupyter上报:ModuleNotFoundError: No module named ‘xgboost‘
    @Async注解的使用方法
    一个ES设置操作引发的“血案”
    思维导图解读《纳瓦尔宝典》
    FTP协议
    [毕业设计]机器学习水域检测标注算法
    Spring编程常见错误50例-Spring Bean依赖注入常见错误(上)
    CUDA编程1--GPU内存模型
  • 原文地址:https://blog.csdn.net/wudi1107/article/details/136460670