0

I am saving a image path to my model image field with custom save function. then i realised that I am just saving the path and not an actual object. my question is how to convert that path to a object using PIL.

Harry
  • 13,091
  • 29
  • 107
  • 167

3 Answers3

7

To change an image path to PIL object, you have to make a request to the image path then convert the content to BytesIO and open it using PIL.Image function.

import requests
from PIL import Image
from io import BytesIO

image_url = "https://recruiterflow.com/blog/wp-content/uploads/2017/10/stackoverflow.png"
response = requests.get(image_url)
img = Image.open(BytesIO(response.content))
output = BytesIO()
img.save(output, format='PNG')
p8ul
  • 2,212
  • 19
  • 19
1

how to convert that path to a object using PIL

If by object you mean reading the image using PIL then you can do the following:

from PIL import Image
image = Image.open(<path>)

I don't know how if you mean something else.

Manoj Govindan
  • 72,339
  • 21
  • 134
  • 141
  • That is what I tried but I get an error: Exception Value:_committed I am getting images form youtube videos with urllib.urlretrieve then once thats done I Image.open(the url of the saved image) and get that error. – Harry Aug 30 '10 at 12:00
  • I assumed that you meant file path of the images rather than URLs. I don't think `open()` is meant for URLs. You'll have to read the image data from the URL and then use `fromstring` or similar. – Manoj Govindan Aug 30 '10 at 12:04
  • The image is already saved to a path on my machine. then I use that path of the image to open() – Harry Aug 30 '10 at 12:05
0

Did you mean something like this:

import urllib, Image
image = urllib.URLopener()
cookie = 'PHPSESSID=4a52...'
image.addheader('Cookie',cookie)
image.retrieve("http://www.your-domain.net/NASA.png", "NASA.png")
im = Image.open("NASA.png")
im.show()
Martin Thoma
  • 124,992
  • 159
  • 614
  • 958