Python - Open image in binary mode with a URL

Viewed 7010

I have a snippet that reads my images locally (returns binary), i.e:

image = 'car.jpg'
with open(image, 'rb') as image_file:
    content = image_file.read()

I'm trying to recreate the same but with images that are hosted on the internet, I have tried with the following but I've had no luck.

from urllib.request import  urlopen
from PIL import Image
import io

url = 'https://somewebsite.com/fm-01/car.jpg'

image = urlopen(url)
image_file = io.BytesIO(image.read())
im = Image.open(image_file)
im = im.tobytes()

EDIT ...

Same exact image, one on google cloud storage and the other one locally. They have different bytes when opening them.

with open('car.jpg','rb') as image_file:
    content = image_file.read()
    print(len(content))

size : 234712

url = 'https://storage.googleapis.com/fm-01/car.jpg'
img = Image.open(urlopen(url))
image = img.tobytes()
print(len(image))

size : 1077600

2 Answers

It is simple as:

from urllib.request import urlopen

url = 'https://somewebsite.com/fm-01/car.jpg'

img = urlopen(url).read()

You have not understood the comment I made explaining exactly this under Mikhail's answer.

The 234,712 bytes is the size of the JPEG-encoded data in the disk file - it includes the image height, width, date, GPS coordinates, camera manufacturer and the all the pixels of the image DCT-compressed into a JPEG.

The 1,077,600 bytes is the size of the array you will need to create in memory to hold the uncompressed red, green and blue pixels in, say 898x400 pixels at 3 bytes (1 red, 1 green and 1 blue) per pixel.

898 * 400 * 3 = 1077600
Related