1

So i have some code that downloads an image, overlays it and shows the result. However I am getting a 403 (probably from user agent) when trying to download from a specific site. How can I create code similar to this that does the same thing?

from PIL import Image
import os, sys
import wget
import requests


url = "https://cdn.discordapp.com/avatars/247096918923149313/34a66572b9339acdaa1dedbcb63bc90a.png?size=256"
filename = wget.download(url)

pp = Image.open(filename)
pp.save("image2c.png")
pp = Image.open("image2c.png").convert("LA")
pp.save("image2c.png")

background = Image.open("image1.png").convert("RGBA")
foreground = Image.open("image2c.png").convert("RGBA")
foreground = foreground.resize((256, 256), Image.BILINEAR)

background.paste(foreground, (125, 325), foreground)
background.show()
os.remove(filename)
bob roberts
  • 31
  • 1
  • 1
  • 2

1 Answers1

1

It seems that wget python library have some problems with either https or parameters... You can use requests (you have already imported it).

from PIL import Image
import os, sys
import requests
from StringIO import StringIO

url = "https://cdn.discordapp.com/avatars/247096918923149313/34a66572b9339acdaa1dedbcb63bc90a.png?size=256"
response = requests.get(url)
pp = Image.open(StringIO(response.content))
pp.save("image1.png")

pp = Image.open("image2c.png").convert("LA")
pp.save("image2c.png")

background = Image.open("image1.png").convert("RGBA")
foreground = Image.open("image2c.png").convert("RGBA")
foreground = foreground.resize((256, 256), Image.BILINEAR)
background.paste(foreground, (125, 325), foreground)
background.show()

SEE: How do I read image data from a URL in Python?

For Python3:

from PIL import Image
import os, sys
import requests
from io import BytesIO

url = "https://cdn.discordapp.com/avatars/247096918923149313/34a66572b9339acdaa1dedbcb63bc90a.png?size=256"
response = requests.get(url)
pp = Image.open(BytesIO(response.content))
pp.save("image1.png")

see: https://stackoverflow.com/a/31067445/8221879

  • I get an error here (using python 3) TypeError: initial_value must be str or None, not bytes – bob roberts Jul 03 '17 at 10:03
  • Hmmm, tested on python2.7. Could you try this sugestion: https://stackoverflow.com/a/31067445/8221879 ? from PIL import Image import os, sys import requests from io import BytesIO url = "https://cdn.discordapp.com/avatars/247096918923149313/34a66572b9339acdaa1dedbcb63bc90a.png?size=256" response = requests.get(url) pp = Image.open(BytesIO(response.content)) pp.save("image1.png") – Robert Szczelina Jul 04 '17 at 10:38