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

PIL - Unable to change the transparency level for JPEG image

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

  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

JPEG 不支持透明度。为了使您的图像具有透明度,您必须将其保存为支持图像透明的格式,例如 PNG.

首先,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.jpgtest.jpg


注意粘贴调用的参数:

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

最后一个参数是图像遮罩。通过提供 RGBA 图像作为遮罩 arg,其 alpha 通道用作遮罩,如 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.