Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

saving a numpy array as a io.BytesIO with jpg format

I am using xlsxwriter to insert image into excel in python code.

Now, I had image data(numpy array) after opencv process. I would like insert this image data to excel. But xlswriter only support io.BytesIO stream.

question: I don't know how to convert numpy array to io.BytesIO with jpg format.

I have trying numpy.tostring but without jpg format.

the code working well in below: _f = open('test.jpg') # I would like to insert test.jpg worksheet.insert_image('E2', 'abc.jpg', {'image_data': _f.read()})

Anybody can help me ? thank you so much.

like image 704
Bob Liu Avatar asked Nov 02 '25 00:11

Bob Liu


1 Answers

Convert the numpy arrays to PIL Image structure, then use BytesIO to store the encoded image.

img_crop_pil = Image.fromarray(numpy_image)
byte_io = BytesIO()
img_crop_pil.save(byte_io, format="JPG")
jpg_buffer = byte_io.getvalue()
byte_io.close()
like image 78
Radek Avatar answered Nov 03 '25 15:11

Radek