Python實現圖片切割


import os
from PIL import Image

def splitimage(src, rownum, colnum, dstpath):
    img = Image.open(src)
    w, h = img.size
    if rownum <= h and colnum <= w:
        print('Original image info: %sx%s, %s, %s' % (w, h, img.format, img.mode))
        print('開始處理圖片切割, 請稍候...')

        s = os.path.split(src)
        if dstpath == '':
            dstpath = s[0]
        fn = s[1].split('.')
        basename = fn[0]
        ext = fn[-1]

        num = 0
        rowheight = h // rownum
        colwidth = w // colnum
        for r in range(rownum):
            for c in range(colnum):
                box = (c * colwidth, r * rowheight, (c + 1) * colwidth, (r + 1) * rowheight)
                img.crop(box).save(os.path.join(dstpath, basename + '_' + str(num) + '.' + ext), ext)
                num = num + 1

        print('圖片切割完畢,共生成 %s 張小圖片。' % num)
    else:
        print('不合法的行列切割參數!')

src = input('請輸入圖片文件路徑:')
if os.path.isfile(src):
    dstpath = input('請輸入圖片輸出目錄(不輸入路徑則表示使用源圖片所在目錄):')
    if (dstpath == '') or os.path.exists(dstpath):
        row = int(input('請輸入切割行數:'))
        col = int(input('請輸入切割列數:'))
        if row > 0 and col > 0:
            splitimage(src, row, col, dstpath)
        else:
            print('無效的行列切割參數!')
    else:
        print('圖片輸出目錄 %s 不存在!' % dstpath)
else:
    print('圖片文件 %s 不存在!' % src)
復制代碼

  然后執行。

  恩,確實很簡單。Python 的庫實在很強大,也很好用。我居然有些不想用 Delphi 寫小工具了:)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM