python实现图片压缩和word排版

由于每月市场考察拍摄不少照片,需要批量将图片在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‘
这是没有读取到图片信息,解决参考,存储路径不能有汉字,需要两个双斜杠。

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')
  • 11
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值