【问题标题】:How to fade image in Python如何在 Python 中淡化图像
【发布时间】:2021-10-15 15:16:36
【问题描述】:

我有以下代码,它只在底部进行淡入淡出,并且它会淡出几乎一半的图像。我怎样才能让它只在底部和顶部淡化 10% 的图像:

from PIL import Image

im = Image.open('1.jpg')
im.putalpha(255)
width, height = im.size
pixels = im.load()
for y in range(int(height*.55), int(height*.75)):
    alpha = 255-int((y - height*.55)/height/.15 * 255)
    for x in range(width):
        pixels[x, y] = pixels[x, y][:3] + (alpha,)
for y in range(y, height):
    for x in range(width):
        pixels[x, y] = pixels[x, y][:3] + (0,)
im.save('1.png')

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    如果你拿了解决方案from here,你应该知道函数的含义。要解决您的问题,只需稍作修改即可:

    im = Image.open('1.png')
    im.putalpha(255)
    width, height = im.size
    pixels = im.load()
    
    def fade_image(image, p1, p2, flow_up=False):
        fade_range = list(range(int(height*p1), int(height*p2)))
        fade_range = fade_range[::-1] if flow_up else fade_range
        for y in fade_range:
            if flow_up:
                alpha = int((y - height*p1)/height/(p2-p1) * 255)
            else:
                alpha = 255-int((y - height*p1)/height/(p2-p1) * 255)
            for x in range(width):
                pixels[x, y] = pixels[x, y][:3] + (alpha,) 
    
    fade_image(pixels, 0.9, 1. , flow_up=False)
    fade_image(pixels, 0  , 0.1, flow_up=True)
    im.save('1.png')
    

    在这里,我假设对于图像顶部的 10%,您需要将其向上淡化,因此从像素索引 0.1 * height0 将 alpha 从 255 线性减小到 0。我删除了最后两个“for 循环”,因为在另一个 StackOverflow 问题中,它需要擦除淡入淡出的底部。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-30
      • 1970-01-01
      • 2011-06-27
      • 1970-01-01
      • 1970-01-01
      • 2014-11-06
      • 2011-11-18
      相关资源
      最近更新 更多