Basically what I want to do is take a file, bring its binary data(decimal of course) into an list and then generate a grayscale bitmap image using PIL based on that list.
For example if the file is 5000 bytes (image size will be 100 x 50) and each byte is an integer between 0 and 255, I want to paint the first byte to the first pixel and go down the row until all bytes are exhausted.
The only thing I got so far is reading the file in:
f = open(file, 'rb')
text = f.read()
for s in text:
print(s)
This outputs the bytes in decimal.
I'm looking for some direction on how to accomplish this. I've done a lot of searching, but it doesn't seem too many have tried doing what I want to do.
Any help would be greatly appreciated!
You could use Numpy's fromfile()
to read it efficiently:
#!/usr/bin/env python3
import numpy as np
from PIL import Image
# Define width and height
w, h = 50, 100
# Read file using numpy "fromfile()"
with open('data.bin', mode='rb') as f:
d = np.fromfile(f,dtype=np.uint8,count=w*h).reshape(h,w)
# Make into PIL Image and save
PILimage = Image.fromarray(d)
PILimage.save('result.png')
Keywords: PIL, Pillow, Python, Numpy, read raw, binary, 8-bit, greyscale grayscale, image, image processing.
I think this should do it. Is scipy
an option?
In [34]: f = open('image.bin', 'r')
In [35]: Y = scipy.zeros((100, 50))
In [38]: for i in range(100):
for j in range(50):
Y[i,j] = ord(f.read(1))
In [39]: scipy.misc.imsave('image.bmp', Y)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With