【问题标题】:Adding watermark to Image in Python using PIL使用 PIL 在 Python 中为图像添加水印
【发布时间】:2018-08-15 06:04:47
【问题描述】:

我正在尝试通过此算法使用 PIL(枕头)向图像添加水印

def watermark_image_with_text(filename):
    text = 'Watermark'
    color = 'blue'
    fontfamily = 'arial.ttf'
    image = Image.open(filename).convert('RGBA')
    imageWatermark = Image.new('RGBA', image.size, (255, 255, 255, 0))
    draw = ImageDraw.Draw(imageWatermark)
    width, height = image.size
    font = ImageFont.truetype(fontfamily, int(height / 20))
    textWidth, textHeight = draw.textsize(text, font)
    x = width / 5
    y = height / 6
    draw.text((x, y), text, color, font)
    my_img = Image.alpha_composite(image, imageWatermark)
    my_img.save('water_' + filename.name)
    return 'water_' + filename.name

它适用于 PNG 文件,但它不适用于其他文件格式的图像,如 JPG、JPEG、TIF 等... 任何人都可以建议一种将水印应用于所有文件格式的图像的通用方法

  • 错误是cannot write mode RGBA as JPEG

【问题讨论】:

    标签: python-3.x image python-imaging-library watermark


    【解决方案1】:

    错误是:

    无法将模式 RGBA 写入 JPEG

    解决方案很简单。保存前将图像转换回 RGB 模式。

    my_img.convert('RGB').save('water_' + filename.name)
    

    这是因为 JPEG 是为照片设计的。因此,它不支持透明度(照片不透明)。您必须明确丢弃透明度数据才能保存 JPEG。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-15
      • 1970-01-01
      • 1970-01-01
      • 2020-12-15
      相关资源
      最近更新 更多