简体   繁体   English

用Python压缩图像(无存档)

[英]Compress Images in Python (No Archive)

I'm writing a Python script that deals with images. 我正在编写一个处理图像的Python脚本。 Is there a module that can compress an image without putting it into an archive, and decompress it back? 是否有一个模块可以压缩图像而不将其放入存档中,然后将其解压缩? (eg A 1MB image is now 0.8MB after compression, then 1MB after decompression). (例如,1MB图像在压缩后现在为0.8MB,然后在解压缩后为1MB)。

Can I see example code of compressing and decompressing an image in Python without the use of archives? 我可以在不使用档案的情况下看到在Python中压缩和解压缩图像的示例代码吗?

I've already taken a look at some modules, but those compress strings. 我已经看过一些模块,但是那些压缩字符串。

You probably want to take a look at the Python Image Library (PIL) , and the PNG and JPEG formats. 您可能想要查看Python图像库(PIL)以及PNGJPEG格式。

The PIL Image.save() method will let you save PNG or JPEG images. PIL Image.save()方法可以保存PNG或JPEG图像。

PNG - Lossless, good for "cartoony"/logo images with solid colors or small numbers of colors. PNG - 无损,适用于纯色或少量颜色的“卡通”/徽标图像。

JPEG - Lossy, good for photos, images with lots "going on". JPEG - 有损,适用于照片,有很多“继续”的图像。

Modern image formats such PNG and JPEG are already compressed and my general recommendation is take Brendan Long's advice and use those formats and exploit all the work that's been put into them. 像PNG和JPEG这样的现代图像格式已经被压缩了,我的一般建议是采用Brendan Long的建议并使用这些格式并利用已经放入其中的所有工作。

That said, if you want to compress the contents of any arbitrary file in Python, here's a very simple example: 也就是说,如果你想在Python中压缩任意文件的内容,这里有一个非常简单的例子:

import zlib

with open("MyImage.jpg", "rb") as in_file:
    compressed = zlib.compress(in_file.read(), 9)

with open("MyCompressedFile", "wb") as out_file:
    out_file.write(compressed)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM