Skip to main content
 首页 » 编程设计

python之PIL之无法更改 JPEG 图像的透明度级别

2025年05月04日22傻小

我正在尝试创建一个图像并用半透明的黑色填充它:

  from PIL import Image 
  from PIL import ImageFont 
  from PIL import ImageDraw 
  from PIL import ImageEnhance 
 
 
  fnt = create_font() 
 
  # my background rectangle 
  img1 = Image.new("RGBA", 100, 100, color=(0, 0, 0, 230)) #RGBA 
  dr1 = ImageDraw.Draw(img1) 
  dr1.text((5, 5), "some text", font=fnt) 
 
  # my source image 
  my_img.paste(dr1, (10, 10)) 
  my_img.save(out_file, "JPEG") 

但它忽略了作为透明度级别的“230”。如果我将其更改为“0”或任何其他数字,则“dr1”矩形的透明度级别 保持不变——它完全是黑色的。

更新:

我在 jpeg my_img 中有一个来源。我想在其部分 img1 上放置一个半透明的矩形,并带有文本。我怎样才能做到这一点?如何让 img1 更透明?

请您参考如下方法:

首先,JPEG 不支持透明度,因此如果您想要具有透明度的图像文件,则需要使用其他格式,例如 PNG。

我不知道 create_font 函数是在哪里定义的;我的 PIL ImageFont 中没有该名称的函数(我在 32 位 Linux 上的 Python 3.6 上使用 PIL.PILLOW_VERSION == '3.3.0')。

此外,粘贴操作将不起作用,但您不需要它。

这是您的代码的修改版本。

from PIL import Image, ImageFont, ImageDraw 
 
img1 = Image.new("RGBA", (100, 100), color=(0, 0, 0, 64)) 
dr1 = ImageDraw.Draw(img1) 
fnt = ImageFont.load_default() 
dr1.text((5, 5), "some text", font=fnt, fill=(255, 255, 0, 128)) 
 
#img1.show() 
img1.save('test.png') 

这是它创建的 PNG 文件:


这是您更新后的问题的一些代码。

from PIL import Image, ImageFont, ImageDraw 
 
img1 = Image.open('hueblock.jpg').convert("RGBA") 
 
overlay = Image.new("RGBA", (100, 100), color=(0, 0, 0, 63)) 
dr1 = ImageDraw.Draw(overlay) 
fnt = ImageFont.load_default() 
dr1.text((5, 5), "some text", font=fnt, fill=(255, 255, 255, 160)) 
 
img1.paste(overlay, (64, 64), overlay) 
img1.show() 
img1.save('test.jpg') 

这里是hueblock.jpg和test.jpg


注意粘贴调用的参数:

img1.paste(overlay, (64, 64), overlay) 

最后一个参数是图像 mask 。通过提供 RGBA 图像作为蒙版 arg,其 alpha channel 用作蒙版,如 the Pillow docs 中所述。

[...] If a mask is given, this method updates only the regions indicated by the mask. You can use either “1”, “L” or “RGBA” images (in the latter case, the alpha band is used as mask). Where the mask is 255, the given image is copied as is. Where the mask is 0, the current value is preserved. Intermediate values will mix the two images together, including their alpha channels if they have them.