wanadev / mozjpeg-lossless-optimization

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

Access cjpeg #1

Closed henri-hulski closed 2 years ago

henri-hulski commented 2 years ago

Hi! Looks quite interesting. Is it also possible to access cjpeg to create new images?

flozz commented 2 years ago

Hello,

Accessing cjpeg is out of the scope of this library (too much work and the cjpeg API is messy / too complicated (IMHO)).

With Python, the simplest way to create JPEGs is probably using Pillow.

:)

henri-hulski commented 2 years ago

Thanks for your answer! At the moment I'm using mozjpeg cjpeg directly from the system. But this is not really reliable when I make a web app for someone else when I don't know his server. So you would suggest to create the image with pillow and optimize it after with this app?

flozz commented 2 years ago

Yes.

Here is an example showing how to open an image with Pillow, then converting it to JPEG and finally optimizing it before writing it on the disk:

#!/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")

(you can of course create a new empty image instead of opening one, etc.)

henri-hulski commented 2 years ago

Thanks! I will try. :)