Szabolcs Dombi
Szabolcs Dombi

Reputation: 5783

Using Pillow Image.tobytes to flip the image and swap the color channels

I have the following code:

img = Image.open('test.jpg')
texture_content = img.tobytes()
...

The texture_content contains the image upside in RGB format.

I want the texture_content to be flipped and to be in BGRA format.

How can I do this directly without using Image.transpose and numpy to swap the color channels?

Upvotes: 1

Views: 1121

Answers (1)

Szabolcs Dombi
Szabolcs Dombi

Reputation: 5783

The documentation of Image.tobytes mentions encoder_name='raw' but does not explain *args.

Here are a couple of examples using the raw encoder:

To flip the image and swap the red and the blue channels:

img.tobytes('raw', 'BGR', 0, -1)

To flip the image:

img.tobytes('raw', 'RGB', 0, -1)

To swap the color channels:

img.tobytes('raw', 'BGR', 0, 1)

To swap the color channels and add an extra channel for alpha:

img.tobytes('raw', 'BGRX', 0, 1)

Unfortunately the alpha values will be 0, to avoid this use Image.convert first:

img.convert('RGBA').tobytes('raw', 'BGRA', 0, 1)

You can use Image.frombuffer to read texture_content back:

Reading texture_content, flip the image and swap the red and the blue channels.

img = Image.frombuffer('RGBA', size, texture_content, 'raw', 'BGRA', 0, -1)

Upvotes: 3

Related Questions