To compress JPEG images using Python, you can use the PIL
(Python Imaging Library) library, which provides various image manipulation functions. Here’s an example of how you can compress a JPEG image:
from PIL import Image
def compress_jpeg(input_image_path, output_image_path, quality):
with Image.open(input_image_path) as image:
image.save(output_image_path, "JPEG", quality=quality)
# Example usage
input_path = "input.jpg"
output_path = "compressed.jpg"
compression_quality = 50 # Adjust the quality value as desired (0-100)
compress_jpeg(input_path, output_path, compression_quality)
In this example, the compress_jpeg()
function takes three parameters: the input image path, the output image path, and the compression quality. The input image is opened using Image.open()
from PIL
, and then it is saved with the desired compression quality using image.save()
.
You can adjust the compression_quality
parameter to a value between 0 and 100, where 0 corresponds to the lowest quality (highest compression) and 100 corresponds to the highest quality (lowest compression).
Make sure you have the PIL
library installed. You can install it using pip
:
pip install pillow
By using the PIL
library, you can easily compress JPEG images by specifying the desired compression quality.
+ There are no comments
Add yours