Cara menggunakan python reduce image size

In this tutorial I will show you how to reduce image size using Python program. I am using Pillow package

for reducing the size of the image. You can reduce the size of image in terms of width and height as well as size of the image in weight (for example, from 100 kb to 30 kb). So, you are basically going to compress the image from both sides.

While reducing the size of an image, you also need to maintain the quality of the image.

Cara menggunakan python reduce image size

Why do you need to reduce?

You might have faced an issue while uploading your image or photo to government portal for KYC purpose or any other purpose where you need to upload your or your family members photos along with other personal details. In such case, your photo size exceeds the allowed size. Let’s say your photo size is 145 KB while allowed size is 100 KB in the portal.

Online tools may not suite your requirements?

There are many online tools/software available to reduce image size, but you may not trust them. Because, these tools may save your uploaded image and you are not sure where your image gets saved in the third party software. So, you want to build your own tool to reduce the size of the image.

Prerequisites

Python 3.9.7, Pillow 8.4.0

Project Directory

Create a project root directory called python-reduce-image-size as per your chosen location. I am also creating other folders where optimized and scaled images will be stored from original images. These folders are – original_images, scaled_images and optimized_images and created inside the project’s root folder.

I may not mention the project’s root directory name in the subsequent sections, but I will assume that I am creating files with respect to the project’s root directory.

Reduce Image Size

Now I am going to create a Python script which will reduce the size of the image significantly. The following Python code is written into reduce_image_size.py script file.

import os, sys
from PIL import Image
 
orig_img_dir = "original_images/"
dirs = os.listdir(orig_img_dir)
 
print('Image Size Reduction Started...')
 
for img in dirs:
    if os.path.isfile(orig_img_dir + img):
        im = Image.open(orig_img_dir + img)
        img_name = os.path.basename(orig_img_dir + img)
        width, height = im.size       
        im = im.resize((width, height), Image.ANTIALIAS)
        im.save('scaled_images/' + img_name)
        #im.save('optimized_images/' + img_name, optimize=True, quality=95)
        im.save('optimized_images/' + img_name, optimize=True, quality=85)
 
print('Image Size Reduction Done.')

In the above program, I have imported the required modules from Python and Pillow packages.

I have kept the images into original_images folder under the same directory where my reduce_image_size.py script is kept.

The scaled_images folder contains the reduced images which are resized without passing optimize and quality parameters. The ANTIALIAS filter produces image with highest quality.

The optimized_images folder contains the reduced images which are resized with optimize and quality parameters. The optimize flag will do an extra pass on the image to find a way to reduce its size as much as possible. The default quality is 75, the quality value 85 will give you the optimized image with smaller size and quality of the image does not get affected much. The quality with 95 will produce image with much bigger size than quality with 85.

Testing the Image Quality after reducing size

Original Images

Here are the following original images downloaded from links – https://file-examples.com/index.php/sample-images-download/ and https://sample-videos.com/download-sample-jpg-image.php for testing purpose.

You can download the images and source code later from this tutorial in the section.

file_example_JPG_2500kB.jpg – 2.38 mb

file_example_PNG_3MB.png – 2.82 mb

SampleJPGImage_20mbmb.jpg – 20.3 mb

Scaled Images

After reducing the image size the scaled image size becomes as given below:

file_example_JPG_2500kB.jpg – 1.03 mb

file_example_PNG_3MB.png – 2.98 mb

SampleJPGImage_20mbmb.jpg – 9.82 mb

Optimized Images

After reducing the image size the optimized image size becomes as given below:

file_example_JPG_2500kB.jpg – 1.69 mb

file_example_PNG_3MB.png – 2.82 mb

SampleJPGImage_20mbmb.jpg – 12.2 mb

If you look at the reduced image size, you can find that one of the images got bigger size than original size. Therefore, you can tweak the parameters to reduce the size of the image.

Pada bahasa pemrograman python kita dapat menampilkan citra menggunakan library tambahan yaitu OpenCV. Cara untuk menginstall OpenCV di python adalah dengan cara mengetikan perintah : pip install opencv-python pada anaconda prompt. Apabila tidak terdapat error, cek apakah OpenCV sudah terinstall dengan sempurna dengan cara mengetikan perintah berikut :

import cv2

print(cv2.__version__)

Hasilnya akan muncul versi dari OpenCV seperti gambar berikut :

Cara menggunakan python reduce image size

Setelah OpenCV terinstall dengan baik, selanjutnya kita akan mencoba untuk load image dengan cara mengetikan perintah berikut ini :

import cv2

img = cv2.imread("spiderman.png", 1)

Pada kode diatas, kita memanggil library OpenCV dengan menambahkan import cv2. Kemudian kita load image dengan menggunakan fungsi

import cv2

img = cv2.imread("spiderman.png", 1)
2. Citra yang kita load adalah citra berwarna RGB, yang dapat diunduh disini. Pada fungsi
import cv2

img = cv2.imread("spiderman.png", 1)
2 terdapat 2 atribut, yang pertama adalah citra yang akan di load, yang kedua adalah mode citra.

  • Mode 1, untuk citra berwarna
  • Mode 2, untuk citra grayscale (abu-abu)

Kemudian citra yang di load, disimpan di variable img. Ketika dijalankan tidak akan menampilkan output apapun. Namun citra akan tersimpan dalam memori penyimpanan sementara. Untuk menampilkan citra, digunakan fungsi

import cv2

img = cv2.imread("spiderman.png", 1)
4 sebagai berikut:

import cv2

img = cv2.imread("spiderman.png", 1)

cv2.imshow("Spiderman", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Fungsi

import cv2

img = cv2.imread("spiderman.png", 1)
4 memiliki 2 atribut, yang pertama adalah judul window, kemudian yang kedua adalah variable image yang akan ditampilkan. Terdapat fungsi
import cv2

img = cv2.imread("spiderman.png", 1)
6 untuk menampilkan window. Parameter 0 pada fungsi
import cv2

img = cv2.imread("spiderman.png", 1)
6artinya ketika kita menekan tombol apapun maka akan menutup window. Jika kita ubah parameter waitKey menjadi 2000 maka window akan terbuka selama 2000ms atau 2 detik kemudian tertutup. Fungsi
import cv2

img = cv2.imread("spiderman.png", 1)
6 selalu berpasangan dengan fungsi
import cv2

img = cv2.imread("spiderman.png", 1)
9, yang bertugas untuk menutup window-window yang sedang aktif. Hasil dari kode program tersebut adalah sebagai berikut.

Cara menggunakan python reduce image size

Menampilkan Atribut Citra

Menggunakan OpenCV dan Python, kita dapat memperoleh atribut atau spesifikasi dari citra. Informasi pertama yang akan kita tampilkan adalah tipe dari citra. Untuk menampilkan tipe citra dapat menggunakan perintah berikut :

import cv2

img = cv2.imread("spiderman.png", 0)
print(type(img))

Perintah

import cv2

img = cv2.imread("spiderman.png", 1)

cv2.imshow("Spiderman", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
0n menampilkan tipe dari citra yaitu

<class 'numpy.ndarray'>

Hal itu menunjukan bahwa sebuah citra itu terdiri dari array yang membentuk matriks. untuk melihat matriks yang dihasilkan beserta nilai piksel nya, tambahkan perintah berikut:

import cv2

img = cv2.imread("spiderman.png", 0)
print((img)

Hasilnya akan mucul sebuah matriks yang berisi nilai piksel dari citra spiderman.png sebagai berikut :

[[ 38  38  38 ...  92  91  90]
 [ 38  38  38 ...  98  97  95]
 [ 38  38  38 ... 101 100  97]
 ...
 [111 111 112 ... 108 106 105]
 [112 112 112 ... 110 108 106]
 [113 113 113 ... 110 109 107]]

Untuk menampilakan ukuran dan dimensi citra dapat menggunakan perintah berikut ini

import cv2

img = cv2.imread("spiderman.png", 0)
print(img.shape) #menampilkan ukuran citra
print(img.ndim) #menampilkan dimensi citra

Hasilnya akan muncul ukuran citra dan dimensi citra sebagai berikut

(551, 600) # ukuran citra, panjang 551, lebar 600
2 # dimensi dari citra

Mengubah Ukuran (Resize) Citra

Mengubah ukuran (memperbesar, memperkecil) citra, dapat dilakukan menggunakan fungsi yang sudah terdapat di OpenCV. Fungsi tersebut adalah

import cv2

img = cv2.imread("spiderman.png", 1)

cv2.imshow("Spiderman", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
1. Cara penggunakan fungsi
import cv2

img = cv2.imread("spiderman.png", 1)

cv2.imshow("Spiderman", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
1 adalah sebagai berikut :

import cv2

img = cv2.imread("spiderman.png", 1)
resize = cv2.resize(img, (200, 200)) # Resize image to 200x200 pixel
cv2.imshow("Spiderman", resize)
cv2.waitKey(0)
cv2.destroyAllWindows()

Kode diatas akan mengubah ukuran citra menjadi 200×200 piksel. Untuk mengatur ukuran secara presisi, semisal memperkecil ukuran menjadi menjadi separuh ukuran semula. Atapun memperbesar ukuran citra menjadi 2 kali ukuran semula. Maka diperlukan operasi artimatika perkalian dan membagian seperti berikut ini

import cv2

img = cv2.imread("spiderman.png", 1)
0

Menyimpan Citra Hasil Modifikasi

Setelah berhasil mengubah ukuran citra, selanjutnya kita simpan citra hasil modifikasi menggunakan perintah

import cv2

img = cv2.imread("spiderman.png", 1)

cv2.imshow("Spiderman", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
3. Kode lengkapnya adalah sebagai berikut :

import cv2

img = cv2.imread("spiderman.png", 1)
1

Pada kode diatas, kita menyimpan citra baru yang memiliki ukuran 2 kali lipat dari citra asli. Nama dari citra baru tersebut adalah “Spiderman_resize.jpg”. Secara tidak langsung saat ini kita memiliki 2 file gambar sebagai berikut :