Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I read a binary file and turn the data into an image?

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!

like image 964
Hussien Hussien Avatar asked Dec 15 '22 23:12

Hussien Hussien


2 Answers

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.

like image 63
Mark Setchell Avatar answered Dec 28 '22 23:12

Mark Setchell


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)
like image 32
Steve Tjoa Avatar answered Dec 29 '22 01:12

Steve Tjoa