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

时间:2022-11-08 00:25:31

I have an image in PIL Image format. I need to convert it to byte array.

我有一个PIL图像格式的图像。我需要将其转换为字节数组。

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

Now I need the roiImg as a byte array.

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

1 个解决方案

#1


40  

Thanks everyone for your help.

谢谢大家的帮助。

Finally got it resolved!!

终于解决了!!

import io

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

imgByteArr = io.BytesIO()
roiImg.save(imgByteArr, format='PNG')
imgByteArr = imgByteArr.getvalue()

With this i don't have to save the cropped image in my hard disc and I'm able to retrieve the byte array from a PIL cropped image.

有了这个,我不必将裁剪后的图像保存在硬盘中,我可以从PIL裁剪图像中检索字节数组。

#1


40  

Thanks everyone for your help.

谢谢大家的帮助。

Finally got it resolved!!

终于解决了!!

import io

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

imgByteArr = io.BytesIO()
roiImg.save(imgByteArr, format='PNG')
imgByteArr = imgByteArr.getvalue()

With this i don't have to save the cropped image in my hard disc and I'm able to retrieve the byte array from a PIL cropped image.

有了这个,我不必将裁剪后的图像保存在硬盘中,我可以从PIL裁剪图像中检索字节数组。