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