Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting jpeg string to PIL image object

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?

like image 313
mt88 Avatar asked Aug 07 '15 17:08

mt88


People also ask

Does PIL work with JPG?

PIL is a free library that adds image processing capabilities to your Python interpreter, supporting a range of image file formats such as PPM, PNG, JPEG, GIF, TIFF and BMP.

How do I PIL an image?

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).

How do you convert an object to an image in Python?

convert() Returns a converted copy of this image. For the “P” mode, this method translates pixels through the palette. If mode is omitted, a mode is chosen so that all information in the image and the palette can be represented without a palette.

What is PIL image object?

PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. PIL. Image. new() method creates a new image with the given mode and size. Size is given as a (width, height)-tuple, in pixels.


1 Answers

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
like image 68
Diego Suarez Avatar answered Oct 11 '22 01:10

Diego Suarez