用python批量缩小图片

九月 10th, 2009 发表评论 阅读评论

现在的数码相机的分辨率越来越大了,随便照一张相片,动不动就是1M,2M一张,在上传到网络上的相册前,有没有想过,有必须放这么清晰的相片到网上吗,现在的免费相册有很多,但多数是有大小限制的,比如1G大小了,对于一些照相爱好者,网上的免费相册很容易就满的哦,况且说实在的,也没必要放清晰这么高的相片到网上了,不如让我们帮这些相片瘦瘦身吧。自己动手,丰衣足食。

使用PIL(Python Imaging Library)处理图片。

 #coding=gbk
#fileName: resizePicture.py
#批量缩小图片,需要安装PIL( Python Imaging Library )
#python resizePicture.py F;\photo F:\photo2  [jpg, [ 0.5] ]

import Image
import os
import sys

def resizeOne(picFile,outFile,rate):
    picF = Image.open(picFile)
    w,h = picF.size
    w,h = int(w*rate),int(h*rate)
    newF = picF.resize( (w,h) )
    newF.save( outFile )

def main(picPath,newPath,picType,rate):
    fileNames = os.listdir( picPath )
    for file in fileNames:
        dotIx = file.rfind('.')
        fileBegin = file[:dotIx ]
        fileType = file[dotIx+1:]
        if fileType.lower()==picType:
            resizeOne( picPath+'\\'+file,
                newPath+'\\'+fileBegin+'_mini.'+fileType, 0.5 )
            print newPath+'\\'+fileBegin+'_mini.'+fileType, 'saved'
   
if __name__ == '__main__':
    picPath = sys.argv[1]
    newPath = sys.argv[2]
    picType = 'jpg'
    rate = 0.5
    if len(sys.argv)>3:
        picType = sys.argv[3]
    if len(sys.argv)>4:
        rate = float( sys.argv[4] )
    if not os.path.isdir(picPath) or not os.path.isdir(newPath):
        print 'The path is incorrect'
        sys.exit()
    main(picPath,newPath,picType.lower(),rate )

 

分类: python学习 标签: 批量缩小图片  Image  PIL  (753次阅读)

  1. 2009-09-10 at 23:05
    Python初学者路过,收藏了
  2. 2009-09-11 at 00:14
    python看不太懂者飘过~~
  3. 2009-09-11 at 00:50
    9月份py的的流行排名好像下降了
  4. 2009-09-11 at 10:01
    @Qing 我也看到这个排行了。php上到第三了 在C++之前了 晕!
  5. 2009-09-12 at 20:37
    php白菜价了……
  6. 2009-09-13 at 00:21
    喜欢python,有待研究~
  7. 2009-09-13 at 12:54
    不懂,但是凑个热闹.
  8. 2009-09-25 at 22:58
    pil站点: http://www.pythonware.com/products/pil/index.htm
    测试PIL有没有载入用 'import Image' 即可
  9. sunny
    2009-10-18 at 15:55
    你好,我照着你的代码敲了一遍,但是有问题,麻烦给解答一下好吗??
    Traceback (most recent call last):
      File "", line 2, in 
        picPath=sys.argv[1]
    IndexError: list index out of range

    不知道怎么修改??
    另外代码的最后一句 是否是自己设定参数调用main函数??

    非常感谢
  10. 2009-10-18 at 23:07
    调用时必须提供至少2个参数的,第一个是图片所在目录,第2个是压缩后图片的保存目录
  11. 2009-11-19 at 13:12
    def main(picPath,newPath,picType,rate):



    def main(picPath,newPath,picType='jpg',rate=0.5):