2

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.stack.imgur.com/zuyvH.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?

Rawnak Yazdani
  • 1,333
  • 2
  • 12
  • 23
  • all of those links contain the file extension (or at least I get redirected to a link that contains the extension and the `requests` should too) – Matiiss Dec 30 '21 at 14:12
  • you don't necessarily need to know the exact extension to save the image, just use `png` or `jpg` and you should be fine – Matiiss Dec 30 '21 at 14:18
  • I have updated my description, but yes you are right. The links which are redirected contain extensions. But, is there a way in Python which simulates this behavior (links do not contain extensions, but redirected links are)? Because this is how pics from lorem picsum are required to be used. – Rawnak Yazdani Dec 30 '21 at 14:18
  • 1
    "and it does not work for an URL without any image file extension (e.g. https://picsum.photos/id/128/100/100)." What do you mean by "does not work"? What happened when you tried using that code? How is the result different from what you expect? Also: are you actually using the `requests` third-party library for this? If not, the `[python-requests]` tag is inappropriate. Either way, you should show at least some code. As a refresher, please read [ask]. – Karl Knechtel Dec 30 '21 at 14:18

1 Answers1

2

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

Kanishk
  • 258
  • 1
  • 3
  • 9
  • 1
    idk the technical name, but they are called f-strings, just fancy way of editing strings. that whole line is equivalent to: `fname = "sample_image."+extension` – Kanishk Dec 30 '21 at 14:57