Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get compressed image byte representation in memory

How can I get the same effect as:

from PIL import Image
with Image.open(image_path) as image:
  image.thumbnail((200, 200), Image.ANTIALIAS)
  image.save(temporary_thumbnail_path)
with open(temporary_thumbnail_path, "rb") as thumbnail_file:
  thumbnail_as_string = base64.b64encode(thumbnail_file.read()).decode()

without having to write to disk ?

i.e. I would like to get the bytes representation of the compressed image, but without having to resort to temporary_thumbnail_path. I know that PIL documentation recommends using

save(), with a BytesIO parameter for in-memory data.

but I am not sure to understand what this means and haven't found examples online.

like image 931
vib Avatar asked Dec 14 '25 05:12

vib


1 Answers

It was not so hard:

import io
from PIL import Image

output = io.BytesIO()
with Image.open(image_path) as image:
  image.thumbnail((400, 400), Image.ANTIALIAS)
  image.save(output, format="JPEG")
  thumbnail_as_string = base64.b64encode(output.getvalue()).decode()
like image 78
vib Avatar answered Dec 16 '25 19:12

vib



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!