简体   繁体   中英

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!

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)

From the PIL Image documentation :

Image.fromstring(mode, size, data)

For your example:

im = Image.fromstring('L', (100, 50), text)

There's also a frombuffer function, but the difference isn't obvious.

I don't think using PIL for this would be incredibly efficient, but you can look into the ImageDraw module if you are looking to paint onto a blank canvas.

My approach would be a bit different: since your file format resembles the Netpbm format very closely, I would try converting it. For simplicity, try adding/manipulating the headers of your format while reading it so that PIL can read it natively.

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