How to save an image from an URL which does not contain any image file extensions (e.g. png) in Python?

Viewed 192

I have read a similar question's answer here, but it only says about an URL that contains an image file extension (e.g. https://i.imgur.com/ExdKOOz.png) and this method does not work for an URL without any image file extension (e.g. https://picsum.photos/id/128/100/100).

I used the code below to save and show an image when the URL does not contain an extension. But it did not work.

import requests
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

response = requests.get("https://picsum.photos/id/128/100/100")

file = open("sample_image.png", "wb")
file.write(response.content)

file.close()

img = mpimg.imread('sample_image.png')
imgplot = plt.imshow(img)
plt.show()

Now, how can I load and save this image in Python?

1 Answers

you can get do the following, after getting the response:

_, extension = response.headers["content-type"].split("/")
fname = f"sample_image.{extension}"
file = open(fname, "wb")
file.write(response.content)
file.close()

Related