11from PIL import Image
2+ import os
23
3- def compress_image (default_image = Image . open ( 'original_image.jpg' ) ):
4- ''' Takes an image file and compress it without losing image quality. '''
4+ def compress_image ():
5+ ''' Takes an image file and compress it without losing image quality. '''
56
6- ''' If no image file is provided, the default image will be compressed '''
7-
8- # Get image 'width' and 'height'
9- w , h = default_image .size
10- # compress image
11- default_image = default_image .resize ((h , w ), Image .ANTIALIAS )
12- # return compressed image
13- return default_image .save ('compressed_image.jpg' )
7+ ''' If no image file is provided, the default image will be compressed '''
8+ try :
9+ image_name = str (input ("Enter the name of the image you want to compress: " ))
10+ default_image = Image .open (f'{ image_name } ' )
11+ except FileNotFoundError :
12+ default_image = Image .open ('original_image.jpg' )
13+
14+ # Get image 'width' and 'height'
15+ w , h = default_image .size
16+ # Separate the file name from the extension
17+ default_image_name = os .path .splitext (os .path .basename (default_image .filename ))
18+ # compress image
19+ default_image = default_image .resize ((w , h ), Image .ANTIALIAS )
20+ # return compressed image
21+ return default_image .save ('{}_compressed{}' .format (default_image_name [0 ], default_image_name [1 ]))
1422
1523# Run
16- compress_image ()
24+ compress_image ()
0 commit comments