crop a b64 image in python

To crop a base64 image in Python, you first need to decode the base64 string into an image, perform the cropping operation, and then encode the cropped image back to base64. Here's an example:

main.py
import base64
from PIL import Image
from io import BytesIO

def crop_base64_image(base64_string, left, top, right, bottom):
    image_data = base64.b64decode(base64_string)
    image = Image.open(BytesIO(image_data))

    width, height = image.size
    cropped_image = image.crop((left, top, right, bottom))

    buffered = BytesIO()
    cropped_image.save(buffered, format="PNG")
    cropped_image_base64 = base64.b64encode(buffered.getvalue()).decode('utf-8')

    return cropped_image_base64

# Example usage
base64_image = "your_base64_string_here"
left = 100
top = 100
right = 300
bottom = 300

cropped_image_base64 = crop_base64_image(base64_image, left, top, right, bottom)
print(cropped_image_base64)
709 chars
27 lines

Make sure to replace "your_base64_string_here" with your actual base64 image string and adjust the left, top, right, and bottom parameters according to your desired cropping dimensions.

gistlibby LogSnag