Skip to content

Latest commit

 

History

History
75 lines (48 loc) · 2.05 KB

Python_Compress_images.md

File metadata and controls

75 lines (48 loc) · 2.05 KB



Template request | Bug report | Generate Data Product

Tags: #python #PIL #images #compress

Author: Mohit Singh

Description: This notebook uses PIL library to compress the image.

Input

Import libraries

try:
    from PIL import Image
except:
    !pip install PIL
    from PIL import Image
import os
import requests

Setup Variables

  • image_url: address of the image file
image_url = "https://source.unsplash.com/user/c_v_r/1900x800"

Model

Saving the image

response = requests.get(image_url)
open("image.jpg", "wb").write(response.content)
## opening the image to work on
image = Image.open("image.jpg")
## getting height and width of image
height, width = image.size

Compressing image

compressed_image = image.resize((height, width), Image.ANTIALIAS)
## saving compressed image
compressed_image.save("compressed_image.jpg", optimize=True, quality=9)

Output

## print the size in bytes of original and compressed image
print("Size of original image in bytes:",os.stat('image.jpg').st_size)
print("Size of compressed image in bytes:",os.stat('compressed_image.jpg').st_size)