使用Pillow和urllib从URL打开图片?

4
这是我的“图片粘贴”程序,旨在将一张图片(这里命名为产品)覆盖在另一张图片(这里命名为背景)上。以前,我只是让程序从我的电脑上获取图片。但我决定添加另一个功能,可以从URL获取它们。电脑部分仍然非常出色。
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)

当我运行它时:
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

我从一个Python 2脚本中获取了程序的那部分内容,但尝试将其转换为Python 3格式,所以我确定错误出现在我的符号标记中。

1个回答

7

您的TypeError应足以说明您正在使用错误的IO类。请更改为:

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

这应该对您有所帮助。


我早就有所怀疑!谢谢! - user3151828

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接