Reputation: 13
I have an 512x512 image file that uses every 4 bytes for a RGBA pixel. Here's an example:
1F 8B 08 00
The first (R), second (G), and third (B) bytes represent the RGB values, with each value ranging from 0 to 255. The last byte (A) represents the alpha channel, also ranging from 0 to 255. If I want a opaque pixel I must replace the last byte with FF (255 when converted to decimal). Once I converted the 4 bytes into RGBA I can use PIL to create the image, with the first 4 bytes being a pixel located in the upper left corner.
Now here is the 4 bytes, converted into a 1x1 RGBA pixel manually: image
And here's the pixel's RGBA values, based on the 4 bytes:
199(R) 239(G) 125(B) 213(A)
Basically, each byte should be converted into a number ranging from 0 to 255, with each 4 bytes being an RGBA value. I can put these values into a tuple, iterating every 4 values as an RGBA pixel, with the first pixel being on the upper left corner of the image.
Upvotes: 1
Views: 1444
Reputation: 207345
The simplest way to read that is with Numpy:
import numpy as np
from PIL import Image
# Load (unzipped) binary file into Numpy array and reshape
na = np.fromfile('a.rgba',dtype=np.uint8).reshape((512,512,4))
# Make into PIL Image and save
Image.fromarray(na).save('result.png')
By the way, you don't really need any Python, you can do it in Terminal with ImageMagick:
magick -depth 8 -size 512x512 RGBA:yourFile.rgba -auto-level result.png
I added -auto-level
just for fun, in order to stretch the contrast.
Here's a third method if you don't use Numpy:
from PIL import Image
# Slurp entire binary file
with open('image.rgba', 'rb') as file:
data = file.read()
# Make into PIL Image with raw decoder
im = Image.frombuffer('RGBA', (512,512), data, 'raw', 'RGBA', 0, 1)
Upvotes: 2