如何在图像颜色为黑色时使用 Pillow 将 PNG 转换为 JPG?
How to Covert PNG to JPEG using Pillow while image color is black?
我查看了以下链接,了解如何将 PNG
转换为 JPG
:
- How to get alpha value of a PNG image with PIL?
- PIL Convert PNG or GIF with Transparency to JPG without
转换按预期进行,但是当图像颜色本身不是黑色时!我有下图:
代码是:
im.convert('RGB').save('test.jpg', 'JPEG')
使整个画面变黑。我应该如何以正确的格式和颜色转换此 PNG?颜色可以是从黑色到白色的任何颜色。
像这样转换,唯一要做的就是找出要设置的背景颜色:
from PIL import Image
im = Image.open(r"C:\pathTo\pen.png")
fill_color = (120,8,220) # your new background color
im = im.convert("RGBA") # it had mode P after DL it from OP
if im.mode in ('RGBA', 'LA'):
background = Image.new(im.mode[:-1], im.size, fill_color)
background.paste(im, im.split()[-1]) # omit transparency
im = background
im.convert("RGB").save(r"C:\temp\other.jpg")
我查看了以下链接,了解如何将 PNG
转换为 JPG
:
- How to get alpha value of a PNG image with PIL?
- PIL Convert PNG or GIF with Transparency to JPG without
转换按预期进行,但是当图像颜色本身不是黑色时!我有下图:
代码是:
im.convert('RGB').save('test.jpg', 'JPEG')
使整个画面变黑。我应该如何以正确的格式和颜色转换此 PNG?颜色可以是从黑色到白色的任何颜色。
像这样转换,唯一要做的就是找出要设置的背景颜色:
from PIL import Image
im = Image.open(r"C:\pathTo\pen.png")
fill_color = (120,8,220) # your new background color
im = im.convert("RGBA") # it had mode P after DL it from OP
if im.mode in ('RGBA', 'LA'):
background = Image.new(im.mode[:-1], im.size, fill_color)
background.paste(im, im.split()[-1]) # omit transparency
im = background
im.convert("RGB").save(r"C:\temp\other.jpg")