Sarath C
Sarath C

Reputation: 237

How to compress quality of conversion JPG to WebP in Python

I'm trying to convert the jpg images into new generation WebP format. I used PIL for that and everything working perfectly! But my problem is when the program compresses a JPG file which is 134KB and when it converted into WebP it became 108KB.

How I can shorten the size of the WebP image ?, I want to compress the quality.

My code looks like this:

from PIL import Image


image = Image.open('my-image.jpg')
image = image.convert('RGB')
image.save('my-image.jpg.webp', 'webp')

Does anybody know how we can again decrease the size of the converted WebP images?

Upvotes: 8

Views: 12047

Answers (3)

Bert Rico
Bert Rico

Reputation: 1

I actually released a project for this recently and it is published on pypi.org you can use pip install img2webp.

from img2webp import convert_image, process_files

# Convert a single image
convert_image("input.jpg", "output.webp", quality=80)

# Convert multiple images
successful, failed = process_files(
    ["input1.jpg", "input2.png"],
    "output_directory",
    quality=80
)

If you have your scripts folder in your PATH environments you can run img2webp and it will show you a simple GUI to allow you to convert that way, or use in your terminal by running img2webp-cli and then path to your file and -o path to your output and you can use -v for verbose.

It is open source so I will add in the github repo as well.

https://pypi.org/project/img2webp/

https://github.com/bytewise-analytics/img2webp

and here is a loom walking through using the CLI and GUI https://www.loom.com/share/caea1e080cce49c19de2c82372a47b99

Upvotes: 0

arjun
arjun

Reputation: 1203

Converting JPG to WebP using OpenCV in Python.

import cv2

jpg_file_path = 'input_image.jpg'
webp_file_path = 'output_image.webp'

# Read the JPG image
jpg_img = cv2.imread(jpg_file_path)

# Save the image in JPG format with specific quality
cv2.imwrite(webp_file_path, jpg_img, [int(cv2.IMWRITE_WEBP_QUALITY), 80])

In the last line, the desired WebP quality has been set to 80. You may change it to required quality. You can choose a quality in the range [0, 100]. Lower the quality, higher the compression, and lower the output WebP image size.

Reference: Python OpenCV – Convert JPG to WebP

Upvotes: 1

Ashish M J
Ashish M J

Reputation: 700

Set the quality parameter while saving the image.

image.save('my-image.jpg.webp', 'webp', optimize = True, quality = 10)

Save the picture with desired quality. To change the quality of image, set the quality variable at your desired level, The more the value of quality variable and lesser the compression

Upvotes: 13

Related Questions