简体   繁体   English

如何使用 Python(枕头)从顶部淡化具有透明度的图像

[英]How to fade an image with transparency from the top using Python (Pillow)

I'm having trouble figuring out how to fade an image that has transparency from the top, I know something like this works, however, manipulating it to fade from the top instead of the bottom is proving quite difficult.我无法弄清楚如何从顶部淡化具有透明度的图像,我知道这样的事情是可行的,但是,将其从顶部而不是底部淡化是非常困难的。 I was wondering if I could get some help.我想知道我是否可以得到一些帮助。

From something like:从类似的东西:

在此处输入图像描述

I am trying to get something like (where the background is transparent, not white, say I want 10% of the top and bottom faded):我试图得到类似的东西(背景是透明的,而不是白色的,说我想要顶部和底部的 10% 褪色):

在此处输入图像描述

There are lots of ways of doing this.有很多方法可以做到这一点。 Here is one method.这是一种方法。 Basically, in order to make an image transparent, you need to create a greyscale alpha/transparency image which is black where you want the image to be transparent and white where you want it to be opaque.基本上,为了使图像透明,您需要创建一个灰度 alpha/透明度图像,在您希望图像透明的地方为黑色,在您希望图像不透明的地方为白色。 Then push that into your image as an alpha layer and save to a format that supports transparency (PNG, TIFF) as opposed to JPEG.然后将其作为 Alpha 层推送到您的图像中,并保存为支持透明度(PNG、TIFF)而不是 JPEG 的格式。

So, starting with this image:所以,从这张图片开始:

在此处输入图像描述

#!/usr/bin/env python3

from PIL import Image

# Load image and get dimensions
im = Image.open('RandomColouredSquares.png')
w, h = im.size

# Make a linear gradient and resize to match width of input image and 10% of its height
gradient = Image.linear_gradient('L')
gradient = gradient.resize((w,int(h/10)))

gradient looks like this: gradient看起来像这样:

在此处输入图像描述

# Make a new, fully opaque transparency layer (i.e. white) to match input image size
alpha = Image.new('L', (w,h), 'white')

# Paste the gradient into the top-left, then flip top to bottom and paste again
alpha.paste(gradient)
alpha = alpha.transpose(Image.Transpose.FLIP_TOP_BOTTOM)
alpha.paste(gradient)

alpha looks like this: alpha看起来像这样:

在此处输入图像描述

# Now push that alpha layer into the original and save
im.putalpha(alpha)
im.save('result.png')

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM