透明区域图片距离获取,裁剪

##对透明图片进行处理,获取透明透明区域图片从上面计算的距离,和从下面计算的距离


from PIL import Image

# 打开图像

imgpath='''D:\\yzm\\img_slider.png'''

# 打开图片文件
img = Image.open(imgpath)
# 获取图片高度和宽度
width,height = img.size
print(height)
# 初始化上下区域高度为0
top_height = 0
bottom_height = 0
# 遍历图片像素
for y in range(height):
    # 初始化不透明像素计数器
    opaque_pixels = 0
    for x in range(width):
        # 获取当前像素的RGBA值
        r, g, b, a = img.getpixel((x, y))
        # 如果当前像素不透明,则增加计数器
        if a != 0:
            opaque_pixels += 1
    # 如果该行存在不透明像素,则判断其位置
    if opaque_pixels > 0:
        if top_height == 0:
            top_height = y
        bottom_height = height - y - 1
# 输出结果
print('上方区域高度为:', top_height)
print('下方区域高度为:', bottom_height)

裁剪透明区域图片,只保留非透明区域, 只裁剪从上面的透明区域和从下面的透明区域,


'''可以使用Python的Pillow库来裁剪图片,其中的crop()方法可以指定裁剪的区域。假设图片文件名为image.png,需要裁剪距离上面100像素,然后从下面开始计算裁剪88像素,则可以使用如下代码:
这个代码使用crop()方法指定裁剪区域,其中左上角的坐标为(0, 100),右下角的坐标为(width, height - 88),即从图片上方100像素处开始裁剪,裁剪到距离下面88像素处。最后使用save()方法保存裁剪后的图片。

'''


from PIL import Image
# 打开图片文件
img = Image.open('4.jpg')
# 获取图片宽度和高度
width, height = img.size
# 指定裁剪区域
cropped_area = (0, 100, width, height - 88)
# 裁剪图片
cropped_img = img.crop(cropped_area)
# 保存裁剪后的图片
cropped_img.save('cropped_image.png')

  目录