Nice Zombies
Nice Zombies

Reputation: 1087

How to convert RGBA bytes to PNG image?

How do I speed this up? My image is composed of binary RGBA colours.

from PIL import Image
redOffset = 0
blueOffset = 2

byte = open("ALWAYSLOADED_384_00.PTX", "rb").read()
width = 256
height = 256
img = Image.new('RGBA', (width, height))
index = 0
for y in range(0, height):
    for x in range(0, width):
        img.putpixel((x,y), (byte[index + redOffset],byte[index + 1],byte[index + blueOffset], byte[index + 3]))
        index += 4
    
img.save("ALWAYSLOADED_384_00.PNG")

Output

Upvotes: 2

Views: 1760

Answers (1)

ypnos
ypnos

Reputation: 52317

Instead of creating a new image, let PIL operate directly on your buffer.

data = open("ALWAYSLOADED_384_00.PTX", "rb").read()
img = Image.frombuffer("RGBA", (256, 256), data, "raw", "RGBA", 0, 1)
img.save("ALWAYSLOADED_384_00.PNG")

Documentation: PIL.Image.frombuffer.

Upvotes: 3

Related Questions