简体   繁体   中英

How can I compress an image in Python?

I'm working on a image transmition project in which my JPEG image must be transfered via LoRa, so there are a lot of limitations.

I'm working transfering the image in small chunks but their actual size aren't good enough and I can't reduce their individual sizes by dividing the image even more cause the time to send each chunk is significative.

So, I'm looking for alternatives to compress the data of these small chunks but didn't found anything in Python that allow me to do this to an Image loaded with Pillow.

Note that I don't want to resize the image, just to compress it's data.

I'm looking for suggestion on how to do this.

Must say that I can change my mind on using Pillow if necessary.

One strange effect that is happening and I don't know why is that I never get a chunk with less than about 600bytes. I need something close to 300 bytes.

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.

That said, if you want to compress the contents of any arbitrary file in Python, here's a very simple example:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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