crop image
unknown
python
a month ago
1.3 kB
4
Indexable
from PIL import Image import os def crop_image(image_path, percentage, output_path=None): try: img = Image.open(image_path) width, height = img.size if percentage == 25: left = width // 2 top = height // 2 right = width bottom = height elif percentage == 50: left = 0 top = height // 2 right = width bottom = height else: raise ValueError("Percentage must be either 25 or 50") cropped_img = img.crop((left, top, right, bottom)) if output_path: output_dir = os.path.dirname(output_path) if output_dir and not os.path.exists(output_dir): os.makedirs(output_dir) cropped_img.save(output_path) print(f"Đã lưu ảnh tại: {output_path}") return cropped_img except Exception as e: print(f"Có lỗi xảy ra: {str(e)}") return None input_image = "TestFolder/Test/4282bfc30859ad07f44811.jpg" output_image_25 = "output_25.jpg" output_image_50 = "output_50.jpg" crop_image(input_image, 25, output_image_25) crop_image(input_image, 50, output_image_50)
Editor is loading...
Leave a Comment