Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resize base64 encoded image in python

I want resize base64 encoded image in python.I searched I could not find. I used Pillow package to do it. However, Pillow has no such kind of feature .

like image 871
Elvin Jafarov Avatar asked Aug 01 '26 05:08

Elvin Jafarov


1 Answers

This code does the job (Python 3):

import io
import base64
from PIL import Image

base64_str = 'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='

buffer = io.BytesIO()
imgdata = base64.b64decode(base64_str)
img = Image.open(io.BytesIO(imgdata))
new_img = img.resize((2, 2))  # x, y
new_img.save(buffer, format="PNG")
img_b64 = base64.b64encode(buffer.getvalue())
print(str(img_b64)[2:-1])

EDIT: Reducing the size of a base64 image does not imply reducing the file size.

like image 92
2badatcoding Avatar answered Aug 02 '26 20:08

2badatcoding



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!