Home > front end >  How to convert RGBA bytes to PNG image?
How to convert RGBA bytes to PNG image?

Time:02-13

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

CodePudding user response:

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.

  • Related