Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open a simple image using streams in Pillow-Python

from PIL import Image


image = Image.open("image.jpg")

file_path = io.BytesIO();

image.save(file_path,'JPEG');


image2 = Image.open(file_path.getvalue());

I get this error TypeError: embedded NUL character on the last statement Image.open on running the program

What is the correct way to open a file from streams?

like image 962
wolfgang3 Avatar asked Mar 29 '15 14:03

wolfgang3


People also ask

How do you insert an image into a Pillow in Python?

To load the image, we simply import the image module from the pillow and call the Image. open(), passing the image filename. Instead of calling the Pillow module, we will call the PIL module as to make it backward compatible with an older module called Python Imaging Library (PIL).

How do I open an image object in Python?

Image. open() Opens and identifies the given image file. This is a lazy operation; this function identifies the file, but the file remains open and the actual image data is not read from the file until you try to process the data (or call the load() method).


2 Answers

http://effbot.org/imagingbook/introduction.htm#more-on-reading-images

from PIL import Image
import StringIO

buffer = StringIO.StringIO()
buffer.write(open('image.jpeg', 'rb').read())
buffer.seek(0)

image = Image.open(buffer)
print image
# <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=800x600 at 0x7FE2EEE2B098>

# if we try open again
image = Image.open(buffer)

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 2028, in open
   raise IOError("cannot identify image file")
IOError: cannot identify image file

Make sure you call buff.seek(0) before reading any StringIO objects. Otherwise you'll be reading from the end of the buffer, which will look like an empty file and is likely causing the error you're seeing.

like image 55
discort Avatar answered Oct 13 '22 01:10

discort


Using BytesIO is much more simple, it took me a while to figure out. This allows you to read and write to zip files for example.

from PIL import Image
from io import BytesIO

# bytes of a simple 2x2 gif file
gif_bytes = b'\x47\x49\x46\x38\x39\x61\x02\x00\x02\x00\x80\x00\x00\x00\xFF\xFF\xFF\x21\xF9\x04\x00\x00\x00\x00\x00\x2C\x00\x00\x00\x00\x02\x00\x02\x00\x00\x02\x03\x44\x02\x05\x00\x3B'
gif_bytes_io = BytesIO() # or io.BytesIO()

# store the gif bytes to the IO and open as image
gif_bytes_io.write(gif_bytes)
image = Image.open(gif_bytes_io)

# optional proof of concept:
# image.show()

# save as png through a stream
png_bytes_io = BytesIO() # or io.BytesIO()
image.save(png_bytes_io, format='PNG')
print(png_bytes_io.getvalue()) # outputs the byte stream of the png
like image 44
Bart.net Avatar answered Oct 12 '22 23:10

Bart.net