Search code examples
pythoncompressionimage-compressionlzma

Image Compression using LZMA Python


Is there any way to compress Images through LZMA using Python. The pre-existing package can compress text files, but I cannot find any way to do so with Images. Any help is great!

Thank you!


Solution

  • lzma docs provide following example of writing compressed file

    import lzma
    data = b"Insert Data Here"
    with lzma.open("file.xz", "w") as f:
        f.write(data)
    

    Observe that data is bytes (b-prefix) thus you might read any file in binary mode and use its' content as data, for example if you have say file named image.png you might do

    import lzma
    with open("image.png", "rb") as f:
        data = f.read()
    with lzma.open("image.png.xz", "w") as f:
        f.write(data)