Python:裁剪图片

2023-01-31 02:01:53 python 图片 裁剪
from PIL import Image

def clipping(img, width):
    '''
    通过获取像素点,然后将像素点等于255(透明),从而完成修剪图片的操作
    :param img: Image对象
    :param width: 要修剪的宽度
    :return:
    '''

    w, h = img.size
    pixdata = img.load()

     # 修剪左边
     for x in range(width):
         for y in range(0, h):
             pixdata[x, y] = 255

     # 修剪右边
     for x in range(w - width, w):
         for y in range(0, h):
             pixdata[x, y] = 255

    # 修剪上边
    for x in range(0, w):
        for y in range(0, width):
            pixdata[x, y] = 255

    # 修剪下边
    for x in range(0, w):
        for y in range(h - width, h):
            pixdata[x, y] = 255

    return img

img = Image.open(filepath)
img = clipping(img, 2)

相关文章