Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get bytes of image in StringIO container

I am am getting an image from email attachment and will never touch disk. Image will be placed into a StringIO container and processed by PIL. How do I get the file size in bytes?

image_file = StringIO('image from email')
im = Image.open(image_file)
like image 652
Tampa Avatar asked Dec 30 '25 14:12

Tampa


1 Answers

Use StringIO's .tell() method by seeking to the end of the file:

>>> from StringIO import StringIO
>>> s = StringIO("foobar")
>>> s.tell()
0
>>> s.seek(0, 2)
>>> s.tell()
6

In your case:

image_file = StringIO('image from email')
image_file.seek(0, 2)  # Seek to the end
bytes = image_file.tell()  # Get no. of bytes
image_file.seek(0)  # Seek to the start
im = Image.open(image_file)
like image 147
James Mills Avatar answered Jan 02 '26 06:01

James Mills