色彩时光 | 记录程序员世界的点点滴滴

python图片压缩处理


网站写文章的时候时常需要压缩图片,如果图片多一张张处理将十分费神,而程序恰恰能轻松解决。在网上搜了一个python图片压缩处理的代码,自己稍作修改拿来己用,具体代码如下:


# encoding=utf-8
#! /usr/bin/env python
#@author www.rgbtime.com
#@version 2016-02-23 23:47
#图片处理模块(缩放)

import os
import Image
import time

#打开图片目录
srcImgFolder = r"D:\imageWeb"
#保存图片目录
saveImgFolder= srcImgFolder+r"\targetImage"
#缩放图片比例(100,200,400,600)
targetWidthArray = (480,)
targetHeightArray=(480,)

def resizeFold(dir_proc):
    for file in os.listdir(dir_proc):
        if dir_proc==saveImgFolder:
            return
        fullFile = os.path.join(dir_proc, file)
        if os.path.isdir(fullFile):
            resizeFold(fullFile)
            continue

        #带有下划线的目标图片不需要处理
        #if fullFile.find("_") != -1:
        #    continue

        #正常图片
        srcImgFullFileName = fullFile
        print "INFO:process file %s" %(os.path.join(dir_proc, file))
        #处理文件
        if os.path.isfile(srcImgFullFileName):
            folderPath = srcImgFullFileName[:srcImgFullFileName.rfind(os.sep)]
            fileName = srcImgFullFileName[srcImgFullFileName.rfind("\\")+1:]

            img = Image.open(srcImgFullFileName)
#           img.show()
            width,height = img.size
            if width>height:
                for targetWidth in targetWidthArray:
                    targetImg = img.resize(
                               (targetWidth, targetWidth * height / width),
                               Image.ANTIALIAS
                               )
                    #newFileName = fileName.split(".")[0] + "_" + str(targetWidth) + "." + fileName.split(".")[1]
                newFileName = str(time.time()) + "_w" + str(targetWidth) + "." + fileName.split(".")[1]
            else:
                for targetHeight in targetHeightArray:
                    targetImg=img.resize(
                        (targetHeight*width/height,targetHeight),
                        Image.ANTIALIAS
                    )
                newFileName = str(time.time()) + "_h" + str(targetHeight) + "." + fileName.split(".")[1]
            targetImg.save(saveImgFolder + os.sep + newFileName, 'jpeg')


if __name__ == "__main__":
    if os.path.exists(srcImgFolder):
        if not os.path.exists(saveImgFolder):
            os.mkdir(saveImgFolder)
        resizeFold(srcImgFolder)
    else:
        print "文件目录不存在"


Python Imaging Library
http://www.pythonware.com/products/pil/


您可能也对下面文章感兴趣:

Write a Comment


* Content (required) 10~500s

分类

热门标签

友情链接