为用Python编写的程序增加透明度

问题描述 投票:0回答:1

我发现这里的一篇文章中的下面的代码非常有用,但是有人可以告诉我如何添加 alpha 通道吗?

我只需要添加从 0 到 100% 的不透明度。我知道 ppm 文件支持它,而且我对 Python 完全陌生。

我尝试将第四个参数添加为 RGB(A),但没有成功。

我正好需要一个由下面的程序生成的 *.ppm 文件,并添加了透明度。

import array
width,height = 800,600

PPMheader = 'P6\n' +str(width) + ' ' +str(height) + '\n255\n'

# Create and fill a red PPM image
image = array.array('B', [255, 0, 0] * width * height)

# Save as PPM image
with open('result.ppm', 'wb') as f:
   f.write(bytearray(PPMheader, 'ascii'))
   image.tofile(f)
python arrays image graphics photoshop
1个回答
0
投票

PPM 图像格式是NetPBM套件的一部分,仅支持 3 个 8/16 位/样本数据的 RGB 通道。

有一个广泛使用的扩展,称为 PAM “便携式任意映射”,它允许使用 alpha/透明度通道。许多 NetPBM 工具以及 ImageMagick 都可以理解该格式,例如您可以使用 magick INPUT.PAM OUTPUT.PNG

 使用 
ImageMagick

将 PAM 图像转换为 PNG

所以,我希望这对你有用。这是一个例子:

#!/usr/bin/env python3

import numpy as np

# Define image dimension and centre in x/y directions
width,height = 800,600
cx = width//2
cy = height//2

PAMheader = f'P7\nWIDTH {width}\nHEIGHT {height}\nDEPTH 4\nMAXVAL 255\nTUPLTYPE RGB_ALPHA\nENDHDR\n'

# Create and fill a fully opaque red PAM image, 4 means RGBA channels
image = np.full((height, width, 4), [255,0,0,255], np.uint8)

# Make middle semi-transparent, i.e. A channel is 128, i.e. image [:,:,3] = 128
image[cy-80:cy+80, cx-80:cx+80, 3] = 128

# Save as PAM image
with open('result.pam', 'wb') as f:
   f.write(PAMheader.encode())
   image.tofile(f)

© www.soinside.com 2019 - 2024. All rights reserved.