Question

This is my "Image Pasting" Program, which is designed to take one image (here named product) and paste it over another image (here named background). Before, I simply had the program get images from my computer. But I decided to add another feature where you can get them from a url. The computer part still works great.

from PIL import Image, ImageFilter
import urllib.request,io
print("ALL IMAGES MUST BE PNG FORMAT")
ext=input("Get Image From Computer or Internet?(c or i)")
if ext == "c":
    path = input("Background Image Path: ")
    fpath = input("Image Path: ")
if ext == "i":
    url = input("Background URL: ")
    furl = input("Image URL: ")
    path = io.StringIO(urllib.request.urlopen(url).read())
    fpath = io.StringIO(urllib.request.urlopen(furl).read())
background = Image.open(path)
product = Image.open(fpath)
x,y=background.size
x2,y2=product.size
xmid,ymid=x/2-(x2/2),y/2-(y2/2)
a=int(xmid)
b=int(ymid)
background.paste(product,(a,b),product)
background.show()
print(a,b)

When I run it:

ALL IMAGES MUST BE PNG FORMAT
Get Image From Computer or Internet?(c or i)i
Background URL: https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcS6pIlao0o52_Sh2n_PLQ53jsI__QDgFxFOQK-WU-TFl0F3XtIm6Q
Image URL: http://3.bp.blogspot.com/-5s8rne3WJuQ/UPTjBcGoBPI/AAAAAAAAA0o/PPxdbY8ZvB4/s1600/44+baixar+download+the+amazing+spider+man+apk+gratis.png
Traceback (most recent call last):
  File "/Users/William/Documents/Science/PYTHON/Image Pasting.py", line 12, in <module>
    path = io.StringIO(urllib.request.urlopen(url).read())
TypeError: initial_value must be str or None, not bytes

I took that part of the program from a Python 2 script, but tried to convert it, so I'm sure the error is in my notation.

Était-ce utile?

La solution

Your TypeError should be enough to indicate that you're using the wrong IO class. Change:

path = io.StringIO(urllib.request.urlopen(url).read())
fpath = io.StringIO(urllib.request.urlopen(furl).read())

To

path = io.BytesIO(urllib.request.urlopen(url).read())
fpath = io.BytesIO(urllib.request.urlopen(furl).read())

And this should work for you.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top