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:



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



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





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.



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:

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.

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“).

Output (truncated):


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“).

Output (truncated):