Jose Alves
Jose Alves

Reputation: 1

Displaying Python Images

Hello I am new to Python, was running a code and want to display the image in the python console.

My code

from PIL import Image
import requests
from io import BytesIO

response = requests.get('https://image.tmdb.org/t/p/w500_and_h282_face/dKxkwAJfGuznW8Hu0mhaDJtna0n.jpg')
img = Image.open(BytesIO(response.content))  

And searching I found this code that I think fit the example:

import os
import io
import requests
from PIL import Image
import tempfile

buffer = tempfile.SpooledTemporaryFile(max_size=1e9)
r = requests.get(img_url, stream=True)
if r.status_code == 200:
    downloaded = 0
    filesize = int(r.headers['content-length'])
    for chunk in r.iter_content():
        downloaded += len(chunk)
        buffer.write(chunk)
        print(downloaded/filesize)
    buffer.seek(0)
    i = Image.open(io.BytesIO(buffer.read()))
    i.save(os.path.join(out_dir, 'image.jpg'), quality=85)
buffer.close() 

If Anyone Knows What's Wrong.

Upvotes: 0

Views: 294

Answers (1)

Yaroslav  Kornachevskyi
Yaroslav Kornachevskyi

Reputation: 1218

import io
import os
import requests
import tempfile
from PIL import Image
from matplotlib import pyplot as plt

img_url = 'https://image.tmdb.org/t/p/w500_and_h282_face/dKxkwAJfGuznW8Hu0mhaDJtna0n.jpg'

buffer = tempfile.SpooledTemporaryFile(max_size=1e9)
r = requests.get(img_url, stream=True)
if r.status_code == 200:
    downloaded = 0
    filesize = int(r.headers['content-length'])
    for chunk in r.iter_content():
        downloaded += len(chunk)
        buffer.write(chunk)
        print(downloaded/filesize)
    buffer.seek(0)
    i = Image.open(io.BytesIO(buffer.read()))
    i.save(os.path.join('.', 'image.jpg'), quality=85)
buffer.close() 

plt.imshow(i)
plt.show()

enter image description here

Upvotes: 1

Related Questions