问题描述
我需要做的是创建一个具有透明背景的.png图像,在其上绘制一些黑色文本,然后使用img.save('target.png', option='optimize')
All I need is to create a .png image with transparent background, draw some text in black on it and save it using img.save('target.png', option='optimize')
PIL似乎会以32位模式自动保存.png图像.保存之前,我可以在不使输出图像看起来更差的情况下减小色彩深度吗?由于它仅包含黑色文本和透明背景,因此我认为减小颜色深度将大大减小文件大小.
It looks like PIL saves .png images in 32-bit mode automatically. Can I reduce the color depth while not making the output images look much worse before saving? Since it contains only black text and transparent background, I think reducing the color depth would greatly reduce file size.
推荐答案
RGBA
模式是唯一支持透明性的模式,它必须为32位:
The RGBA
mode is the only mode that supports transparency, and it is necessarily 32 bits:
L (8位像素,黑白)
P (8位像素,使用调色板映射到任何其他模式)
P (8-bit pixels, mapped to any other mode using a color palette)
RGB (3x8位像素,真彩色)
RGB (3x8-bit pixels, true color)
RGBA (4x8位像素,带有透明蒙版的真彩色)
RGBA (4x8-bit pixels, true color with transparency mask)
我建议您以非透明的 1 模式存储图像,并使用图像本身作为遮罩.如果为图像提供 1 模式作为蒙版,则黑色像素将保留,而白色像素将变为透明. 这将减少32倍的空间,而不会丢失任何信息.
I would recommend you to store your image with a non-transparent 1 mode and use the image itself as a mask. If you give your image with mode 1 as a mask on your image, black pixels will stay and white ones will be transparent. This will take 32 times less space without any loss of information.
它看起来像这样:
your_transparent_image.paste(bw_image, mask=bw_image)
其中bw_image
是您的黑白文本.
这篇关于使用PIL优化.png图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!