Skip to content

Instantly share code, notes, and snippets.

@DJStompZone
Created November 29, 2023 02:32
Show Gist options
  • Save DJStompZone/4d2aa8827dd46f40063c0123b32fcfe3 to your computer and use it in GitHub Desktop.
Save DJStompZone/4d2aa8827dd46f40063c0123b32fcfe3 to your computer and use it in GitHub Desktop.
Crop an Image With Pillow
from PIL import Image
import io
from typing import Tuple, Optional, Bytes
def crop_image(image_bytes: Bytes, new_size: Optional[Tuple[int, int]] = (2400, 2400)) -> Bytes:
"""
Crops an image from a byte buffer to a specified size and returns the cropped image as a byte buffer.
This function takes an image in the form of a byte buffer, crops it to the specified dimensions,
and returns the cropped image as a byte buffer. The cropping is centered, meaning the function
calculates the coordinates to ensure the cropped area is centered in the original image.
Parameters:
image_bytes (bytes): A byte buffer of the image to be cropped.
new_size (Optional[tuple], optional): The size of the cropped image in pixels, given as
(width, height). Default is (2400, 2400). If None, the original size is used.
Returns:
bytes: The cropped image as a byte buffer.
Author:
DJ (dj@deepai.org)
License:
MIT License
Note:
This function requires the Pillow library (PIL) to handle image operations.
The input and output of the function are both byte buffers, making it suitable
for processing binary image data, such as from HTTP requests.
"""
# Load the image from byte buffer
img = Image.open(io.BytesIO(image_bytes))
# If new_size is None, use the original image size
if new_size is None:
new_size = (img.width, img.height)
# Calculate cropping coordinates
left = (img.width - new_size[0]) // 2
top = (img.height - new_size[1]) // 2
right = (img.width + new_size[0]) // 2
bottom = (img.height + new_size[1]) // 2
# Crop the image
cropped_img = img.crop((left, top, right, bottom))
# Save the cropped image to a byte buffer
img_byte_arr = io.BytesIO()
cropped_img.save(img_byte_arr, format='PNG')
img_byte_arr = img_byte_arr.getvalue()
return img_byte_arr
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment