StringIO无法识别图像文件错误

3

我正在使用以下代码从网络上获取图片:

import Image
import urllib2
import cStringIO

url = 'http://storage.googleapis.com/bloomsky-img/k65x5Kvpyc3W08jBqJ1kqZqnnZapoQ==.jpg'
img = urllib2.urlopen(url).read()
# error occurred when executing the line below
im = Image.open(cStringIO.StringIO(img))
im.verify()
# must reload the image after verify method !!
im = Image.open(cStringIO.StringIO(img))
im.save('name', 'JPEG')

当运行时,出现错误提示:图像无效且错误代码为无法识别图像文件<StringIO.StringIO instance at 0x7f6825b12e18>。但是相同的代码在我的Mac上完美运行。只有当我将代码部署到Ubuntu服务器时,才遇到这样的问题。我检查了文档,并认为我正在正确使用StringIO。有人能帮忙吗?非常感谢。

如果你将 img 保存到文件中 — open("foo.jpg", "w").write(img) — 你能用图像查看器打开那个文件吗?还是它也是损坏的? - David Wolever
@DavidWolever 我正在使用终端操作远程服务器,所以无法检查是否可以使用图像查看器打开它。但是我尝试了你的建议,确实可以将其保存为jpg文件。 - J Freebird
@DavidWolever 这个 URL 是有效的,我可以在浏览器中打开并查看图像。 - J Freebird
@RonKlein 我编辑了这个问题。我认为JFIF文件使用JPEG标准进行压缩,所以格式不应该是一个问题。 - J Freebird
1
你的问题说stringio是罪魁祸首。如果是pillow,那么你有不同的问题。获取文件,保存它,并使用open(<file>)来排除stringio。你写的代码对我来说可以使用预览打开文件。 - Jonathan
显示剩余5条评论
2个回答

2
今日免费次数已满, 请开通会员/明日再来
    --------------------------------------------------------------------
    PIL SETUP SUMMARY
    --------------------------------------------------------------------
    version      Pillow 2.8.2
    platform     linux2 2.7.6 (default, Mar 22 2014, 22:59:56)
                 [GCC 4.8.2]
    --------------------------------------------------------------------
    *** TKINTER support not available
    (Tcl/Tk 8.6 libraries needed)
    *** JPEG support not available
    *** OPENJPEG (JPEG2000) support not available
    --- ZLIB (PNG/ZIP) support available
    *** LIBTIFF support not available
    *** FREETYPE2 support not available
    *** LITTLECMS2 support not available
    *** WEBP support not available
    *** WEBPMUX support not available
    --------------------------------------------------------------------
    To add a missing option, make sure you have the required
    library, and set the corresponding ROOT variable in the
    setup.py script.
    To check the build, run the selftest.py script.
    changing mode of build/scripts-2.7/pilconvert.py from 644 to 755
    changing mode of build/scripts-2.7/pildriver.py from 644 to 755
    changing mode of build/scripts-2.7/pilfile.py from 644 to 755
    changing mode of build/scripts-2.7/pilprint.py from 644 to 755
    changing mode of build/scripts-2.7/pilfont.py from 644 to 755
    changing mode of [...]
Successfully installed Pillow-2.8.2

看到那边的*** JPEG支持不可用了吗?我认为这就是关键...


1
你需要倒带你的stringIO对象 - 只需在验证之前和Image.open之前调用im.seek(0)(并将im传递给它,无需创建另一个stringIO对象);

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