12
votes

I've been handed a list of files from the backend of an application that are supposed to be jpeg files. However for the life of me I haven't been able to convert them into PIL image objects. When I call

str(curimg)

I get back:

<type 'str'>

. I have tried using open(), .read, io.BytesIO(img.read() and also doing nothing to it, but it keeps seeing it as a string. When i print the string, I get unrecognizable characters. Does anyone know how to tell python how to intepret this string as a jpeg and convert it into a pill image where I can call .size and np.array on?

3
Does this question have the answer you seek?Octopus
Did you try Image.fromstring() ?Anand S Kumar
^^ The only thing is I dont know how to get the size that fromstring() needs? All i'm given is a string.mt88

3 Answers

12
votes

You should be able to pass a StringIO object to PIL and open it that way.

ie:

from PIL import Image
import StringIO
tempBuff = StringIO.StringIO()
tempBuff.write(curimg)
tempBuff.seek(0) #need to jump back to the beginning before handing it off to PIL
Image.open(tempBuff)
23
votes

The same thing but a bit simpler

from PIL import Image
import io
Image.open(io.BytesIO(image))

Note:

If image is on the web; you need to download it first.

import requests
image = requests.get(image_url).content  #download image from web

And then pass it to io module.

io.BytesIO(image)

If image is in your hd; you can open directly with PIL.

Image.open('image_file.jpg')  #image in your HD
2
votes

For me, none of the solutions above worked.

I finally managed to read the string properly like this:

from PIL import Image
img = Image.frombytes('RGB', (640, 480), img_str, 'raw')

To test it, you can do something like

image = Image.open("some.png")
print(image.mode, image.size) # OUT: 'RGB' (640, 480)
image = Image.frombytes('RGB', (640, 480), image.tobytes(), 'raw')
image.show()