【问题标题】:Transparency not showing in Python after I cropped it and added transparency裁剪并添加透明度后,透明度未在 Python 中显示
【发布时间】:2016-06-06 16:21:58
【问题描述】:

我正在尝试打开添加了透明角的图像。我将它保存为 .png,当我在 python 中打开它时,角落仍然存在,但是当我在预览中打开相同的图像时,边缘存在。我也在使用 Pillow 进行图像处理。

我尝试添加圆角的图像也是黑白“1”位像素深度。我还尝试在添加角之前和之后将其转换为“RGBA”,我也尝试过使用“RGB”进行相同的操作,但无济于事。

这是我用来制作透明角的方法。

from PIL import Image, ImageChops, ImageOps, ImageDraw
'''
http://stackoverflow.com/questions/11287402/how-to-round-corner-a-logo-without-white-backgroundtransparent-on-it-using-pi
'''
def add_corners(self, im, rad):
    circle = Image.new('L', (rad * 2, rad * 2), 0)
    draw = ImageDraw.Draw(circle)
    draw.ellipse((0, 0, rad * 2, rad * 2), fill=255)
    alpha = Image.new('L', im.size, 255)
    w, h = im.size
    alpha.paste(circle.crop((0, 0, rad, rad)), (0, 0))
    alpha.paste(circle.crop((0, rad, rad, rad * 2)), (0, h - rad))
    alpha.paste(circle.crop((rad, 0, rad * 2, rad)), (w - rad, 0))
    alpha.paste(circle.crop((rad, rad, rad * 2, rad * 2)), (w - rad, h - rad))
    im.putalpha(alpha)
    return im

【问题讨论】:

  • 你是怎么调用函数的?例如,您可以将其传递为 JPG 文件,但必须将返回值另存为 PNG,否则透明度信息将丢失。
  • img2 = add_corners("theFirst.png") img2.save("1234.png", **png_info) img3 = Image.open("1234.png") img3.show() 它仍然不会显示我应用的更改。但它保存正确,真的很奇怪。
  • 如果您使用的是 Windows,show() 会将您的图像显示为 BMP,遗憾的是它也不支持透明度。
  • 我用的是Mac,不知道有没有同样的问题
  • 我不能说 Mac,但在 Windows 上,它确实会在窗口顶部显示临时文件的名称,这表明它具有 BMP 扩展名。

标签: python image python-imaging-library pillow


【解决方案1】:

您拥有的功能应该可以完美运行。您可以将其传递给 JPG 图像,但您必须将生成的文件保存为 PNG 格式,因为 JPG 不支持透明度。例如:

img = Image.open('test.jpg')
img_corners = add_corners(img, 40)
img_corners.save('with_corners.png')

注意,如果使用img_corners.show(),在 Windows 上这将导致库创建一个不支持透明层的 BMP 格式的临时文件。

【讨论】:

    猜你喜欢
    • 2016-12-02
    • 2012-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-05
    • 2016-10-25
    • 2014-09-04
    • 2023-04-07
    相关资源
    最近更新 更多