美文网首页
python 图片批量编辑尺寸

python 图片批量编辑尺寸

作者: 不务正业的设计师 | 来源:发表于2021-01-13 17:37 被阅读0次

这几天接到公司设计方面的需求,需要将几十张图片统一修改为固定的尺寸(1080*1080),其实通过ps动作批处理可以完成。但是如果没有安装ps咋办嘞?或者懒得打开ps,可以考虑通过pyhton快速处理

注意事项

  • 存在图片为长方形或者正方形的情况
  • 存在图片格式的差异化

方法如下:

import cv2
import os

outtype = '.png'  #   <---------- 输出的统一格式
image_size_h =0
image_size_w = 300  #  <---------- 设定长
source_path = "E:\\domo\\pic"+"\\"  #  <---------- 源文件路径
target_path = "E:\\newdomo"+"\\"  #  <---------- 输出目标文件路径
 
if not os.path.exists(target_path):
    os.makedirs(target_path)
 
image_list = os.listdir(source_path)  # 获得文件名
 
i = 0
for file in image_list:
    i = i + 1
    image_source = cv2.imread(source_path + file)  # 读取图片d
    print("处理中-->",file)
    if image_source.shape[0] == image_source.shape[1]:    #图片是正方形
        image_size_h = image_size_w
        image = cv2.resize(image_source, (image_size_w, image_size_h), 0, 0, cv2.INTER_LINEAR)  # 修改尺寸
        # cv2.imwrite(target_path + str(i) + outtype, image)  # 重命名并且保存 (统一图片格式)
        cv2.imwrite(target_path + str(file),image)  # 保留原命名
    else:   #图片是非方形
        sizenum = image_source.shape[0]/image_source.shape[1]
        image_size_h =sizenum * image_size_w 
        image = cv2.resize(image_source, (image_size_w, int(image_size_h)), 0, 0, cv2.INTER_LINEAR)  # 修改尺寸
        # cv2.imwrite(target_path + str(i) + outtype, image)  # 重命名并且保存 (统一图片格式)
        cv2.imwrite(target_path + str(file),image) # 保留原命名
print("批量处理完成")


相关文章

网友评论

      本文标题:python 图片批量编辑尺寸

      本文链接:https://www.haomeiwen.com/subject/othpaktx.html