bob roberts
bob roberts

Reputation: 31

Creating similar behaviour without a 403? (Python Wget)

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)

Upvotes: 1

Views: 116

Answers (1)

Robert Szczelina
Robert Szczelina

Reputation: 63

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

Upvotes: 1

Related Questions