一篇文章搞懂python圖片裁切的問題


import os
import shutil

from PIL import Image


# 獲取path目錄下的所有文件
def get_imlist(path):
    return [os.path.join(path, f) for f in os.listdir(path)]


def cut_img(path="demo"):
	paths = path +"/"
	# 判斷一下用於儲存裁切後的文件夾是否存在 存在刪除,不存在創建
    if os.path.exists(paths):
        shutil.rmtree(path)
        os.mkdir(path)
    else:
        os.mkdir(path)
    # 獲取上傳路徑內的文件列別
    directorys = get_imlist(paths)
    for directory in directorys:
        # 判斷不是圖片文件就跳過(我這裏只處理jpg和png的圖片  也可以加上jpeg的)
        if not (directory.endswith('.jpg') or directory.endswith('.png')):
            pass

        else:
            s = "/"
            try:
                img = Image.open(directory)
                # 提取源圖片的名字 用不裁切後的圖片名字使用
                oimage_name = directory[directory.rfind(s) + 1:]
                (oimage_width, oimage_height) = img.size
                # 根據圖片的寬和高,截取所需要的圖片尺寸
                l = int(oimage_width / 40)  # 左邊裁剪掉多少像素
                u = int(oimage_height / 9)  # 上邊裁剪掉多少像素
                r = 39 * int(oimage_width / 40) # 右邊裁剪掉多少像素
                d = 39 * int(oimage_height / 40)# 下邊裁剪掉多少像素
                # 獲取到新的圖片對象
                cropped = img.crop((l, u, r, d))
                # 保存到新的路徑下 
                cropped.save("./" + paths + "/" + "%s" % oimage_name)
            except:
            	# 異常處理 爲了保證圖片數量和裁剪前一直,把出錯的圖片也放到裁剪後的文件夾中,也可以換成一個新的文件夾
                oimage_name = directory[directory.rfind(s) + 1:]
                with open(directory, "rb") as f:
                    response = f.read()
                with open("./" + paths + "/" + "%s" % oimage_name, "wb") as f1:
                    f1.write(response)
                

if __name__ == '__main__':
	# 傳入你的圖片文件路徑
    cut_img("./path")
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章