Python Code to Reduce and Compress Image Files

As a large number of Internet users use cell phones to access online content, Google started penalizing websites that are slow and take several seconds to download all the data. If your web pages have only text data, you may not have to worry. But if your web pages have image files, you just cannot add the original pictures captured using the latest cameras to your web pages. You have to shrink images to make Google and other search engines happy.

There are many websites that have online tools/applications to shrink image files. But most of those websites allow one image at a time. If you have 100s of image files, you will waste several minutes in shrinking your images. Python has the Python Image Library (PIL) to reduce and compress image files. I have written the following Python code using PIL to reduce and compress image files. Check out the code and let me know if it helps.

import os
from PIL import Image

def getNewSize(img):
	'''
	This function determines the new size of the image.
	Change the below logic as per your desired size.
	'''
	(w,h) = img.size
	(nw,nh) = img.size
	if (w > 1000):
		nw = 1000
		nh = int((1.0*h/w)*nw)
	elif (h > 1200):
		nh = 1200
		nw = int((1.0*w/h)*nh)
	return (nw,nh)

def compressResizeImages(val):
	'''
	This function compresses and resizes the images present in the input folder.
	'''
	extns = ['.jpg','.jpeg','.png','.gif'] #extensions for images
	bytesSaved = 0
	files = next(os.walk(inFolder))[2]
	for file in files:
		if (file[-4:] in extns or file[-5:] in extns):
			print ('processing file....>>> {0}'.format(file))
			imgFile = inFolder + file #input image file path
			outImg = outFolder + file #output image file path
			oSize = os.path.getsize(imgFile) #size of the original image
			inImg = Image.open(imgFile)
			size = getNewSize(inImg)
			inImg.thumbnail(size,Image.ANTIALIAS) # resize the image
			inImg.save(outImg, "JPEG", quality=val)
			nSize = os.path.getsize(outImg) #size of the new image
			bytesSaved = bytesSaved + (oSize - nSize)
	return bytesSaved

def main():
	'''
	This program will compress all images present in the input folder.
	'''
	quality = 50 #1-worst & 100:best
	bytesSaved = compressResizeImages(quality)
	print ('\nTotal Kbytes saved after resizing and compression....{0}'.format(bytesSaved/1000))

#####INPUT OUTPUT FOLDERS##################
inFolder = 'path_to_the_folder_of_your_original_images'
outFolder = 'path_to_the_folder_of_your_shrinked_images'
############################################
if __name__ == '__main__':
	main()
Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.