2

Ok so i have this code:

from PIL import Image
import os, sys
import requests
from io 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()

This returns the error: TypeError: initial_value must be str or None, not bytes

I can't see where I'm going wrong. Can anyone help?

bob roberts
  • 31
  • 1
  • 1
  • 2

1 Answers1

4

response is binary data (bytes) and Image also expects some binary data.

So:

pp = Image.open(StringIO(response.content))

is injecting a text-based IO object in the middle: cannot convert bytes to text (and the next problem would be: cannot read text data into the image)

Fix:

from io import BytesIO
pp = Image.open(BytesIO(response.content))

EDIT: even better, use Image.open(response.raw) like answered here: How to download image using requests

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219