简体   繁体   中英

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")

输出

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM