脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python实现批量压缩图片

Python实现批量压缩图片

2021-01-09 00:12小墨青 Python

这篇文章主要为大家详细介绍了Python实现批量压缩图片的方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文为大家分享了Python实现批量压缩图片的具体代码,供大家参考,具体内容如下

?
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
# -*- coding: utf-8 -*-
"""
__author__= 'Du'
__creation_time__= '2018/1/5 10:06'
"""
 
import os
from PIL import Image
import glob
 
DIR = 'C:/Users/Public/Pictures/Sample Pictures/'
 
class Compress_Picture(object):
  def __init__(self):
    # 图片格式,可以换成.bpm等
    self.file = '.jpg'
 
  # 图片压缩批处理
  def compressImage(self):
    for filename in glob.glob('%s%s%s' % (DIR, '*', self.file)):
      # print(filename)
      # 打开原图片压缩
      sImg = Image.open(filename)
      w, h = sImg.size
      print(w, h)
      dImg = sImg.resize((200, 200), Image.ANTIALIAS) # 设置压缩尺寸和选项,注意尺寸要用括号
 
      # 如果不存在目的目录则创建一个
      comdic = "%scompress/"%DIR
      if not os.path.exists(comdic):
        os.makedirs(comdic)
 
      # 压缩图片路径名称
      f1 = filename.split('/')
      f1 = f1[-1].split('\\')
      f2 = f1[-1].split('.')
      f2 = '%s%s1%s'%(comdic, f2[0], self.file)
      # print(f2)
      dImg.save(f2) # save这个函数后面可以加压缩编码选项JPEG之类的
      print("%s compressed succeeded"%f1[-1])
 
 
if __name__ == "__main__":
  obj = Compress_Picture()
  obj.compressImage()

效果图:

Python实现批量压缩图片

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://blog.csdn.net/qq_34218221/article/details/78979224

延伸 · 阅读

精彩推荐