Convert Image Into Byte Array in Python

Python’s built-in bytearray function allows us to convert arrays to byte arrays. Because an image is just an array of numbers, we will leverage this method to convert images into a byte array.

What is Python bytearray?

The bytearray method returns a Python bytearray object, an array of the given bytes. The bytearray class is a mutable sequence of integers from 0 to 255.

The general syntax for the bytearray method is given below:

bytearray([source[, encoding[, errors]]])

The bytearray method takes three optional parameters- source, encoding, and errors where

  • source is provided as initialization to the array. This parameter can take different data types – strings, integers, or an iterable,
  • encoding – encoding to be used if the source is a string,
  • errors – action to be taken whenever encoding fails for a given character.

Based on our application, we will investigate how bytearray works with integers and iterables (like lists and arrays) as the source. It is important to note that bytearray objects are always generated by calling the constructor since they lack a specialized literal syntax.

If the source is an integer, the array will have that size and be initialized with null bytes. The array can only contain integer elements between 0 and 256 (exclusive) when a source is an iterable object.

Let’s see some examples:

print(bytearray(4))

Output:

bytearray(b'\x00\x00\x00\x00')

As expected, the output contains four null bytes because we initialized the array with an integer 4.

print(bytearray([45]))
print(bytearray([45, 8, 102, 102, 103]))

Output:

bytearray(b'-')
bytearray(b'-\x08ffg')

This time, we passed a list (an iterable), and the output bytearray reflects what we expect.

print(bytearray([199, 45, 253]))

Output:

bytearray(b'\xc7-\xfd')
import numpy as np
print(bytearray(np.array([199, 45, 253])))

Output:

bytearray(b'\xc7\x00\x00\x00\x00\x00\x00\x00-\x00\x00\x00\x00\x00\x00\x00\xfd\x00\x00\x00\x00\x00\x00\x00')

In the above two examples, we passed a list of integers and a Numpy array of the same list of values. The two examples have similar outputs, but Numpy presents its output as an 8-byte size.

Lastly, let’s now convert a deeper array.

import numpy as np
array = np.array([[[199, 45, 253], [102, 102, 103]]])
a = bytearray(array)
print(a)

Output:

bytearray(b'\xc7\x00\x00\x00\x00\x00\x00\x00-\x00\x00\x00\x00\x00\x00\x00\xfd\x00\x00\x00\x00\x00\x00\x00f\x00\x00\x00\x00\x00\x00\x00f\x00\x00\x00\x00\x00\x00\x00g\x00\x00\x00\x00\x00\x00\x00')

Now that we have seen how the bytearray method works on smaller data objects let’s now work on converting an image into a byte array.

Convert Image Into Byte Array

In this section, we will save the following image as “image.jpeg” and use it in our examples.

Figure 1: An image of two puppies. Source: https://www.rawpixel.com/search/dogs

Method 1: The simple one

This method opens the image in reading mode and converts it into a bytearray object using the bytearray method we discussed earlier.

with open("image.jpeg", "rb") as image:
  f = image.read()
  b = bytearray(f)

Method 2: Casting PIL Image into bytearray

If you are using PIL to open your image you can convert the open PIL object into bytearray using the io module as follows (If you do not have PIL installed you can install it with “pip install pillow“).

import io
from PIL import Image
# Open image using the pillow package
img = Image.open("image.jpeg")
# initialiaze io to_bytes converter
img_byte_arr = io.BytesIO()
# define quality of saved array
img.save(img_byte_arr, format='JPEG', subsampling=0, quality=100)
# converts image array to bytesarray
img_byte_arr = img_byte_arr.getvalue()
print(img_byte_arr)

Output (truncated):

B'\xff\xd8\xff\xe0...\xff\xd9'

Method 3: Converting OpenCV Image into bytearray

If you are loading your image using OpenCV then this method is for you. You can proceed as follows (if you do not have cv2 installed install it using pip by running the command “pip install opencv-python“).

import cv2
# Load image (it is loaded as BGR by default)
image = cv2.imread('image.jpeg')
# Conver array to RGB
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# image encoding
success, encoded_image = cv2.imencode('.jpeg', image)
# convert encoded image to bytearray
content_bytes = encoded_image.tobytes()
print(content_bytes)

Output (truncated):

b‘\xff\xd8\xff\xe0...\xff\xd9'