将PIL图像转换为字节数组?

132

我有一张以PIL图像格式存在的图片,我需要将它转换为字节数组。

img = Image.open(fh, mode='r')  
roiImg = img.crop(box)

现在我需要将roiImg作为字节数组。


2
请提供更多细节。字节数组应该是什么格式?原始像素值可以通过Image.getdata()获得,它返回PIL在特定平台上使用的图像的内部表示格式。 - dhke
不确定,但是听起来你需要使用 Imagegetdata() 方法。 - martineau
我的目标是将图像以BLOB类型保存在MySQL数据库中。 - Evelyn Jeba
imgByteArr = open("foo.png", 'rb').read() 需要以与imgByteArr相同的格式获得roiImg。 - Evelyn Jeba
4个回答

286

感谢大家的帮助。

终于解决了!!

import io
from PIL import Image

img = Image.open(fh, mode='r')
roi_img = img.crop(box)

img_byte_arr = io.BytesIO()
roi_img.save(img_byte_arr, format='PNG')
img_byte_arr = img_byte_arr.getvalue()

有了這個,我不需要將裁剪後的圖像保存在我的硬盤中,並且可以從 PIL 裁剪後的圖像檢索字節數組。


1
谢谢您提供这个例子!我正尝试做完全相同的事情。 - Cory
3
请添加 import io? - Ran Locar
10
format="jpg" 时,保存为字节不起作用,而 "jpeg" 对于文件和字节都有效,而 "jpg" 仅对文件有效。 - Evgeny Nozdrev
1
我该如何做这个的反向操作?有什么想法吗? - Mooncrater
2
@Mooncrater 我认为是这样的:stream = io.BytesIO(img_byte_array) 然后 img = Image.open(stream) - Sean McCarthy
显示剩余2条评论

62

这是我的解决方案:

from PIL import Image
import io

def image_to_byte_array(image: Image) -> bytes:
  # BytesIO is a file-like buffer stored in memory
  imgByteArr = io.BytesIO()
  # image.save expects a file-like as a argument
  image.save(imgByteArr, format=image.format)
  # Turn the BytesIO object back into a bytes object
  imgByteArr = imgByteArr.getvalue()
  return imgByteArr

UTF 返回的是什么? - Blue Robin

8

我认为你可以直接调用 PIL 图像的 .tobytes() 方法,然后使用内置的 bytes 将其转换为数组。

#assuming image is a flattened, 3-channel numpy array of e.g. 600 x 600 pixels
bytesarray = bytes(Image.fromarray(array.reshape((600,600,3))).tobytes())

9
根据文档 https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.tobytes ,不建议使用它,因为它会保存每个像素的原始图像数据。如果您使用PNG、JPG等格式,则需要在Image.save()中使用BytesIO()。 - XCanG
啊,我明白了。对于我的目的,我不需要字节数据,因为我立即对RGB值进行数字处理。此外,问题并未提及保存图像,只是转换它们。考虑因此撤销您的负投票。 - Chris Ivan

-4

Python读取文件并提取二进制数组

import base64
with open(img_file_name, "rb") as f:
    image_binary = f.read()
    base64_encode = base64.b64encode(image_binary)
    byte_decode = base64_encode.decode('utf8')

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