[ 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:\t" + im.filename)
    print("format:\t\t" + im.format)
    print("size:\t\t" + str(im.size))
    print("mode:\t\t" + 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))

  

猜你喜欢

转载自www.cnblogs.com/coder211/p/9055969.html