wanadev / mozjpeg-lossless-optimization

Python library to optimize JPEGs losslessly using MozJPEG
Other
34 stars 2 forks source link

Accept bitmap images as input. #2

Closed 2brownc closed 2 years ago

2brownc commented 2 years ago

Currently only jpeg images are supported as input. mozjpeg accepts bmp images so also support bmp images as input.

flozz commented 2 years ago

Hello,

The scope of this library is only to optimize (losslessly) an already existing JPEG. I have currently no time to do more.

But you can use Pillow to open any image format, then converting it to JPEG and finally optimize it with MozJPEG. I wrote an example in issue https://github.com/wanadev/mozjpeg-lossless-optimization/issues/1:

#!/usr/bin/env python3

from io import BytesIO

from PIL import Image
import mozjpeg_lossless_optimization

def convert_to_optimized_jpeg(input_path, output_path):
    jpeg_io = BytesIO()

    with Image.open(input_path, "r") as image:
        image.convert("RGB").save(jpeg_io, format="JPEG", quality=90)

    jpeg_io.seek(0)
    jpeg_bytes = jpeg_io.read()

    optimized_jpeg_bytes = mozjpeg_lossless_optimization.optimize(jpeg_bytes)

    with open(output_path, "wb") as output_file:
        output_file.write(optimized_jpeg_bytes)

if __name__ == "__main__":
    convert_to_optimized_jpeg("img.png", "optimized.jpeg")
2brownc commented 2 years ago

The scope of this library is only to optimize (losslessly) an already existing JPEG. I have currently no time to do more.

I see, okay.

Thank you for the example!!!

flozz commented 2 years ago

I added the example to the README as it may be useful: