python 使用 PIL 优化 .png 图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1991929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 23:30:10  来源:igfitidea点击:

Optimize .png images with PIL

pythonimageoptimizationpngpython-imaging-library

提问by Hyman

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')

我所需要的只是创建一个具有透明背景的 .png 图像,在其上绘制一些黑色文本并使用 img.save('target.png', option='optimize')

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.

看起来 PIL 会自动以 32 位模式保存 .png 图像。我可以减少颜色深度,同时不让输出图像在保存前看起来更糟吗?由于它只包含黑色文本和透明背景,我认为减少颜色深度会大大减少文件大小。

回答by Beno?t Pilatte

The RGBAmode is the only mode that supports transparency, and it is necessarily 32 bits:

RGBA模式是唯一支持透明的模式,必须是32位的:

1(1-bit pixels, black and white, stored with one pixel per byte)

L(8-bit pixels, black and white)

P(8-bit pixels, mapped to any other mode using a color palette)

RGB(3x8-bit pixels, true color)

RGBA(4x8-bit pixels, true color with transparency mask)

1(1位像素,黑白,每字节一个像素存储)

L(8 位像素,黑白)

P(8 位像素,使用调色板映射到任何其他模式)

RGB(3x8 位像素,真彩色)

RGBA(4x8 位像素,带透明蒙版的真彩色)

I would recommend you to store your image with a non-transparent 1mode and use the image itself as a mask. If you give your image with mode 1as 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.

我建议您使用非透明1模式存储图像,并将图像本身用作蒙版。如果您将模式1的图像用作图像上的蒙版,黑色像素将保留,白色像素将透明。这将减少 32 倍的空间,而不会丢失任何信息。

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.

您可以使用“1”、“L”或“RGBA”图像(在后一种情况下,alpha 波段用作遮罩)。在掩码为 255 的情况下,给定的图像按原样复制。如果掩码为 0,则保留当前值。中间值会将两个图像混合在一起,包括它们的 alpha 通道(如果有的话)。

It will look something like this:

它看起来像这样:

your_transparent_image.paste(bw_image, mask=bw_image)

where bw_imageis your black and white text.

bw_image你的黑白文本在哪里。