Closed henri-hulski closed 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.
:)
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?
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.)
Thanks! I will try. :)
Hi! Looks quite interesting. Is it also possible to access cjpeg to create new images?