gpt4 book ai didi

python - PIL 值错误 : not enough image data?

转载 作者:太空宇宙 更新时间:2023-11-03 15:32:09 26 4
gpt4 key购买 nike

当我尝试从 URL 获取图像并将其响应中的字符串转换为 App Engine 中的 Image 时,我收到了上述消息的错误。

from google.appengine.api import urlfetch

def fetch_img(url):
try:
result = urlfetch.fetch(url=url)
if result.status_code == 200:
return result.content
except Exception, e:
logging.error(e)

url = "http://maps.googleapis.com/maps/api/staticmap?center=Narita+International+Airport,Narita,Chiba+Prefecture,+Japan&zoom=18&size=512x512&maptype=roadmap&markers=color:blue|label:S|40.702147,-74.015794&markers=color:green|label:G|40.711614,-74.012318&markers=color:red|color:red|label:C|40.718217,-73.998284&sensor=false"

img = fetch_img(url)
# As the URL above tells, its size is 512x512
img = Image.fromstring('RGBA', (512, 512), img)

根据 PIL ,大小选项假设是一个像素元组。这是我指定的。谁能指出我的误解?

最佳答案

image 返回的数据是图像本身而不是 RAW RGB 数据,因此您不需要将其作为原始数据加载,而是只需将该数据保存到文件中,这将是一个有效图像或使用 PIL 来打开它,例如(我已将您的代码转换为不使用 appengine api,以便任何安装了普通 python 的人都可以运行该示例)

from urllib2 import urlopen
import Image
import sys
import StringIO

url = "http://maps.googleapis.com/maps/api/staticmap?center=Narita+International+Airport,Narita,Chiba+Prefecture,+Japan&zoom=18&size=512x512&maptype=roadmap&markers=color:blue|label:S|40.702147,-74.015794&markers=color:green|label:G|40.711614,-74.012318&markers=color:red|color:red|label:C|40.718217,-73.998284&sensor=false"
result = urlopen(url=url)
if result.getcode() != 200:
print "errrrrr"
sys.exit(1)

imgdata = result.read()
# As the URL above tells, its size is 512x512
img = Image.open(StringIO.StringIO(imgdata))
print img.size

输出:

(512, 512)

关于python - PIL 值错误 : not enough image data?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8328198/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com