1
+ # Importing Image class from PIL module
2
+ from PIL import Image
3
+
4
+ def crop ():
5
+ # Taking the image path as an input
6
+ file_path = str (input ('Enter the image path (absolute path): ' ))
7
+
8
+ # Opening image with an RGB mode, works only with jpeg/jpg formats
9
+ img = Image .open (file_path , mode = "r" )
10
+
11
+ # Calculating size of the original image in pixels for reference
12
+ width , height = img .size
13
+ print ('the old width is: ' + str (width ) + ' and the old height is: ' + str (height ))
14
+
15
+ # Taking left, top, right, bottom points for the cropped image as input
16
+ # Image pixels coorginate grid: X increases from left to right, Y increases from top to bottom
17
+ left = int (input ('Enter the new left point: ' ))
18
+ top = int (input ('Enter the new top point: ' ))
19
+ right = int (input ('Enter the new right point: ' ))
20
+ bottom = int (input ('Enter the new bottom point: ' ))
21
+
22
+ # Crop the image with specified points
23
+ cropped_img = img .crop ((left , top , right , bottom ))
24
+
25
+ # Save the cropped image as a separate image named "cropped_img.jpg" under a specified directory
26
+ cropped_image_path = str (input ('Enter the path to save the cropped image (absolute path): ' ))
27
+ cropped_img .save (f"{ cropped_image_path } /cropped_img.jpg" )
28
+
29
+ # Show the image in the image viewer
30
+ cropped_img .show ()
31
+
32
+ if __name__ == '__main__' :
33
+ crop ()
0 commit comments