为什么我在 Windows 上从 Pillow 得到 "Not Enough Image Data",而同样的代码在 Linux 上运行良好?

Why do I get "Not Enough Image Data" from Pillow on Windows, while the same code works well on Linux?

我们正在尝试将在 Linux 上运行良好的家庭作业的支持文件移植到 Windows。作业的一部分要求学生处理原始图像数据,支持文件使用 Python 在原始数据和图像文件之间进行转换。将图像文件转换为原始数据的代码为:

import os, sys
from PIL import Image
from struct import *

fileName = sys.argv[1]
try:
    myImg = Image.open(fileName)
    width,height = myImg.size
    sys.stdout.write(pack("ii",width,height))
    rgbImg = myImg.convert("RGB")
    pixels = rgbImg.getdata()
    for (r,g,b) in pixels:
        sys.stdout.write(pack("BBB", r,g,b)) 
except IOError, e:
    print >> sys.stderr, "%s: %s\n\nCannot open or understand %s" % (sys.argv[0], str(e), fileName)

而转换回来的代码是:

import os, sys
from PIL import Image
from struct import *

fileName = sys.argv[1]
try:
    dimensions = sys.stdin.read(2*4)
    width,height = unpack("ii", dimensions)

    pixels = sys.stdin.read(3*width*height)
    myImg = Image.frombytes("RGB", (width, height), pixels, "raw", "RGB", 0, 1)
    myImg.save(fileName, "PNG")
except IOError, e:
    print >> sys.stderr, "%s: %s\n\nCannot open or write to %s" % (sys.argv[0], str(e), fileName)

标准输出和输入被重定向到测试设施代码中的文件。该代码在 Linux 上运行良好,但在 Windows 上运行不佳。尝试在 Windows 上写入图像文件时,我们总是遇到以下错误:

Traceback (most recent call last):
  File "image-rewrite.py", line 16, in <module>
    myImg = Image.frombytes("RGB", (width, height), pixels, "raw", "RGB", 0, 1)
  File "C:\Python27\lib\site-packages\PIL\Image.py", line 2100, in frombytes
    im.frombytes(data, decoder_name, args)
  File "C:\Python27\lib\site-packages\PIL\Image.py", line 742, in frombytes
    raise ValueError("not enough image data")
ValueError: not enough image data

你知道发生了什么事吗?非常感谢。

使用stdin / stdout 在Windows 上传输二进制数据是个坏主意。 Windows 使用 CRLF ('\r\n' ) 作为行尾标记,并在输入时转换为 \n 并在输出时转换回来;翻译过程会对二进制数据造成严重破坏。

相反,您应该使用命名文件,并以二进制模式打开它们。


顺便说一句,在 Python 3 中,您不能直接从/向 sys.stdin / sys.stdout 读取/写入二进制数据,即使在 Linux 上也是如此。相反,您需要使用 read / write 方法 sys.stdin.buffer / sys.stdout.buffer.