Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert PIL image to bytearray

In C#, I can use Bitmap.lockbits() to access a bitmap as a byte array. How to do this in PIL? I have tried Image.write() but it wrote a full format image to a stream.

like image 213
J.Doe Avatar asked Jul 28 '16 03:07

J.Doe


People also ask

How do I convert an image to a Bytearray?

Read the image using the read() method of the ImageIO class. Create a ByteArrayOutputStream object. Write the image to the ByteArrayOutputStream object created above using the write() method of the ImageIO class. Finally convert the contents of the ByteArrayOutputStream to a byte array using the toByteArray() method.

How can I get bytes from image in PIL?

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 because PIL does not know the image format in this case. The bytes string can be retrieved using getvalue() method of buf variable.

What is Type Bytearray?

The bytearray type is a mutable sequence of integers in the range between 0 and 255. It allows you to work directly with binary data. It can be used to work with low-level data such as that inside of images or arriving directly from the network. Bytearray type inherits methods from both list and str types.

How do you extract bytes of an image in Python?

path. getsize() is a method of the os module that is used to get the size of a specified path. Pass the image path to this function to get the size of the image file in bytes.


2 Answers

from io import BytesIO
from PIL import Image

with BytesIO() as output:
    with Image.open(path_to_image) as img:
        img.save(output, 'BMP')
    data = output.getvalue()
like image 65
Sergey Gornostaev Avatar answered Oct 07 '22 05:10

Sergey Gornostaev


.. warning::

This method returns the raw image data from the internal storage. For compressed image data (e.g. PNG, JPEG) use :meth:~.save, with a BytesIO parameter for in-memory data.

This is the warning in the tobytes method. So we can use the save method with a BytesIO parameter to get a compressed byte array.

import io

byteIO = io.BytesIO()
image.save(byteIO, format='PNG')
byteArr = byteIO.getvalue()
like image 21
Lynn Han Avatar answered Oct 07 '22 05:10

Lynn Han