zoukankan      html  css  js  c++  java
  • [ Python ] PIL

    示例代码

    # coding: utf-8
    
    from PIL import Image
    import os, sys
    
    Int_Len = 5
    
    def getPicInfo(pic):
        im = Image.open(pic)
        print("--------------------")
        print("file name:	" + im.filename)
        print("format:		" + im.format)
        print("size:		" + str(im.size))
        print("mode:		" + im.mode)
        return im
    
    
    def convertFormat(pic, format):
        pathNew = getNewFormatPath(pic, format)
        try:
            im = Image.open(pic)
            im.save(pathNew, format)
            getPicInfo(pathNew)
            return pathNew
        except IOError:
            print("Cannot create new Format %s for %s." % format, pic)
            return None
    
    
    def convertThumbnails(pic, rate=1, format='JPEG'):
        pathNew = getThumbnailsPath(pic, r"thumbnails", format)
        if (pic != pathNew):
            try:
                im = Image.open(pic)
                size = (int(im.size[0] * rate), int(im.size[1] * rate))
                im.thumbnail(size)
                im.save(pathNew, format)
                getPicInfo(pathNew)
                return pathNew
            except IOError:
                print("Cannot create thumbnail for ", pic)
                return None
    
    
    def getNewFormatPath(pic, format):
        pathSegs = os.path.splitext(pic)
        count = 1
        while True:
            pathNew = pathSegs[0] + r"-" + str(count).zfill(Int_Len) + "." + format.lower()
            if os.path.exists(pathNew):
                count += 1
                pathNew = pathSegs[0] + r"-" + str(count).zfill(Int_Len) + "." + format.lower()
            else:
                return pathNew
    
    
    def getThumbnailsPath(pic, suffix, format):
        pathSegs = os.path.splitext(pic)
        count = 1
        while True:
            pathNew = pathSegs[0] + r"-" + str(count).zfill(Int_Len) + r"-" + suffix + "." + format.lower()
            if os.path.exists(pathNew):
                count += 1
                pathNew = pathSegs[0] + r"-" + str(count).zfill(Int_Len) + r"-" + suffix + "." + format.lower()
            else:
                return pathNew
    
    
    if __name__ == "__main__":
        pic1 = r"res/MIT-001.jpg"
        pic2 = r"res/MIT-002.jpg"
    
        # im = getPicInfo(pic1)
        # r,g,b = im.split()
        # r.rotate(45).show()
        # g.resize((100,200)).show()
        # b.show()
        # im.convert("L").convert("RGB").show()
    
        # convertThumbnails(pic1, 0.5)
    
        path = convertFormat(pic1, 'PNG')
        print(os.path.abspath(path))
    

      

  • 相关阅读:
    100722B
    6-排列
    5-分西瓜差最小(背包 || dfs)
    4-计算九位数以内各个位数字和为s的种类
    3-计算01串
    2-计算星期几(基姆拉尔森计算公式)
    1-作业题构成单调曲线的点数最多
    12-分苹果(递归)
    11-砝码分配(利用3进制)
    10-约瑟夫环的几种解法
  • 原文地址:https://www.cnblogs.com/coder211/p/9055969.html
Copyright © 2011-2022 走看看