# Introduction

Sometimes, we want an in-momery jpg or png image that is represented as binary data. But often, what we have got is image in numpy ndarray or PIL Image format. In this post, I describe how to convert numpy image or PIL Image object to binary data without saving the underlying image.

If the image file is saved on disk, we can read it directly in binary format with open() method by using the b flag:

with open('test.jpg', 'rb') as f:


Now the image will be read from disk to memory and is still in binary format.

But if we want to resize the original image and convert it to binary data without saving the resized image and re-read it from the hard disk, how should we do it?

# Convert image to bytes

We can do it with the help of OpenCV or PIL.

## OpenCV

This is how to achieve that in OpenCV:

import cv2

im_resize = cv2.resize(im, (500, 500))

is_success, im_buf_arr = cv2.imencode(".jpg", im_resize)
byte_im = im_buf_arr.tobytes()

# or using BytesIO
# io_buf = io.BytesIO(im_buf_arr)
# byte_im = io_buf.getvalue()


A little explanation here. imencode() will encode the numpy ndarray in the specified format. This method will return two values, the first is whether the operation is successful and the second is the encoded image contained in an one-dimension array.

Then you can convert the returned array to real bytes either with the tobytes() method or io.BytesIO(). We can finally get the byte_im. It is the same with saving the resized image and then reading it in binary format. But the saving step is removed and all the operation is done in memory.

## PIL

If you like to use PIL for image processing. You can use the following code:

from PIL import Image

im = Image.open('test.jpg')
im_resize = im.resize((500, 500))
buf = io.BytesIO()
im_resize.save(buf, format='JPEG')
byte_im = buf.getvalue()


In the above code, we save the im_resize Image object into BytesIO object buf. Note that in this case, you have to specify the saving image format. The bytes string can be retrieved with getvalue() method of buf variable.
{"ft_lang_label":"__label__en","ft_lang_prob":0.72247237,"math_prob":0.86805105,"size":2571,"snap":"2019-51-2020-05","text_gpt3_token_len":640,"char_repetition_ratio":0.111414105,"word_repetition_ratio":0.015706806,"special_character_ratio":0.25476468,"punctuation_ratio":0.12277228,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9560641,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2020-01-29T19:17:02Z\",\"WARC-Record-ID\":\"<urn:uuid:bcffce1f-0eb8-474f-969b-c26a2930d820>\",\"Content-Length\":\"21228\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:8d50eaa3-1e75-4527-97dd-c4147039668f>\",\"WARC-Concurrent-To\":\"<urn:uuid:455c3e52-e21d-48a5-b7f9-11a71b95b1be>\",\"WARC-IP-Address\":\"185.199.108.153\",\"WARC-Target-URI\":\"https://jdhao.github.io/2019/07/06/python_opencv_pil_image_to_bytes/\",\"WARC-Payload-Digest\":\"sha1:DLSYCJKZCYGGALVBJ6CLNMAAC25O5WES\",\"WARC-Block-Digest\":\"sha1:TLHNYEE4ACHGPN74Z3CJPEUWYWLJXXNW\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2020/CC-MAIN-2020-05/CC-MAIN-2020-05_segments_1579251801423.98_warc_CC-MAIN-20200129164403-20200129193403-00143.warc.gz\"}"}