且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在python中将字节数组转换为图像

更新时间:2022-04-17 14:49:11

您可以生成一个 bytearray 的虚拟对象表示这样的渐变的数据:

You can generate a bytearray of dummy data representing a gradient like this:

import numpy as np

# Generate a left-right gradient 242 px wide by 266 pixels tall
ba = bytearray((np.arange(242) + np.zeros((266,1))).astype(np.uint8)) 

作为参考,该数组将包含以下数据:

For reference, that array will contain data like this:

array([[  0.,   1.,   2., ..., 239., 240., 241.],
       [  0.,   1.,   2., ..., 239., 240., 241.],
       [  0.,   1.,   2., ..., 239., 240., 241.],
       ...,
       [  0.,   1.,   2., ..., 239., 240., 241.],
       [  0.,   1.,   2., ..., 239., 240., 241.],
       [  0.,   1.,   2., ..., 239., 240., 241.]])

然后制作成如下所示的PIL /枕头图像:

And then make into a PIL/Pillow image like this:

from PIL import Image

# Convert bytearray "ba" to PIL Image, 'L' just means greyscale/lightness
im = Image.frombuffer('L', (242,266), ba, 'raw', 'L', 0, 1)

然后,您可以像这样保存图像:

Then you can save the image like this:

im.save('result.png')

文档在此处