将PIL图像转换为bytearray

2024-05-16 05:21:33 发布

您现在位置:Python中文网/ 问答频道 /正文

在C#中,我可以使用Bitmap.lockbits()以字节数组的形式访问位图。在皮尔怎么做?我试过Image.write(),但它向流中写入了完整格式的图像。


Tags: 图像image字节格式数组形式writebitmap
2条回答
from io import BytesIO
from PIL import Image

with BytesIO() as output:
    with Image.open(path_to_image) as img:
        img.save(output, 'BMP')
    data = output.getvalue()

.. warning::

This method returns the raw image data from the internal storage. For compressed image data (e.g. PNG, JPEG) use :meth:~.save, with a BytesIO parameter for in-memory data.

这是tobytes方法中的警告。因此,我们可以使用带BytesIO参数的save方法来获取压缩字节数组。

import io

byteIO = io.BytesIO()
image.save(byteIO, format='PNG')
byteArr = byteIO.getvalue()

相关问题 更多 >