小编Zeb*_*lon的帖子

使用Pillow和Python 3从RGB列表创建图像

我有一个RGB数据列表:

cdata=[R1, G1, B1, R2, G2, B2,..., Rn, Gn, Bn]
Run Code Online (Sandbox Code Playgroud)

其中每个值都介于0到255之间。

我正在尝试使用Pillow 5.0.0将这个数组重建为图像。在Python 2下,我能够通过以下方式将值列表转换为字节字符串:

        cdata2 = []
        gidx = len(cdata)//3
        bidx = len(cdata)//3*2
        for i in range(len(cdata)//3):
            cdata2.append(cdata[i])
            cdata2.append(cdata[i+gidx])
            cdata2.append(cdata[i+bidx])

        data = ""
        for c in cdata2:
            data += chr(c)

        im = Image.frombytes("RGB", (420, 560), data)
Run Code Online (Sandbox Code Playgroud)

然后在base64中重新编码“ im”,并在HTML模板中将其显示为PNG。

不幸的是,这在Python 3中不起作用,我遇到了类似以下错误:

UnicodeEncodeError: 'charmap' codec can't encode characters in position 42099-42101: character maps to <undefined>
Run Code Online (Sandbox Code Playgroud)

此外,Pillow 5文档现在建议使用

im = Image.open(StringIO(data))
Run Code Online (Sandbox Code Playgroud)

但无法使其与上面构建的我的字符串一起使用。还有其他更聪明的方法吗?在此先感谢您的帮助。

python image stringio python-imaging-library pillow

5
推荐指数
1
解决办法
2330
查看次数

标签 统计

image ×1

pillow ×1

python ×1

python-imaging-library ×1

stringio ×1