Image Optimization Using Python

Optimizing images is essential for enhancing website performance and boosting SEO. With the emergence of WebP format, we can now offer high-quality images with significantly reduced file sizes, thereby improving loading times and user experience. In this article, we’ll explore how to convert JPEG and PNG images into the WebP format using Python and the Pillow library, making the process simple and accessible.
from PIL import Image
import imageio
import io
def opt_img(in_path, out_path, quality=98):
 img = Image.open(in_path)
    out_buffer = io.BytesIO()
    img.save(out_buffer, format="JPEG", quality=quality, optimize=True)  
    with open(out_path, "wb") as out_file:
        out_file.write(out_buffer.getvalue())
in_image_path = "input_image.jpg"  
out_image_path = "output_image_optimized.jpg" 
opt_img(in_image_path, out_image_path)
print("Image optimization completed.")

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top