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

时间:2014-01-02 03:44:17

标签: python url urllib pillow

这是我的“图像粘贴”程序,旨在拍摄一张图像(此处命名为产品)并将其粘贴到另一张图像(此处命名为背景)上。之前,我只是让程序从我的电脑中获取图像。但我决定添加另一个功能,您可以从网址获取它们。计算机部分仍然很好用。

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脚本中获取了该程序的那部分,但是尝试将其转换,所以我确定错误在我的表示法中。

1 个答案:

答案 0 :(得分:6)

您的TypeError应该足以表明您使用的是错误的IO类。变化:

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

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

这应该适合你。