Convert jpeg string to PIL image object

I was handed a list of files from the backend of the application that should be jpeg files. However, for my life, I have not been able to convert them to PIL image objects. When i call

str(curimg)

      

I'm coming back:

<type 'str'>

      

... I tried to use open (),. Read, io.BytesIO (img.read () and also do nothing with it, but it keeps seeing it as a string. When I print a string, I get unrecognizable characters. How to say python, how to intepret this string as jpeg and convert it to thumbnail where can i call .size and np.array?

+3


source to share


2 answers


You have to pass a StringIO object to PIL and open it that way.

t



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)

      

+7


source


The same, but a little simpler

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

      

Note:

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

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

      



And then pass it to the io module.

io.BytesIO(image)

      

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

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

      

+1


source







All Articles