Home > Enterprise >  How to display an unknown-size bytes sequence as a grey image in Python
How to display an unknown-size bytes sequence as a grey image in Python

Time:01-16

I have a bytes sequence, which is the content of an executable file read from disk. Now I want to create an image from these bytes and display it as a grey image, like this:

sample image

How can I achieve this in Python?

CodePudding user response:

One possible solution is to convert the binary executable file to a ppm image, which is a very simple image format. This can be done by reading in the bytes one at a time from the file and appending them as RGB values to the end of the PPM file. Here is example code from my github repo:

import os
import math
import sys

if len(sys.argv) < 2:
    print("usage: bin_to_ppm.py [PATH]")
    print("PATH is the path to the binary file to inspect")
    sys.exit()

input_file_path = sys.argv[1]

input_file = open(input_file_path,"rb")
output_file = open('output.ppm', 'w')
file_array = []
pixels_written = 0

file_size = os.path.getsize(input_file_path)
width = 300
height = math.ceil(file_size/width)

output_file.write("P3 \n")#header
output_file.write(str(width)   " ")#width
output_file.write(str(height)   " \n")#height
output_file.write("255 \n")

byte = input_file.read(1) #get first byte
while byte: 
    x = str(int.from_bytes(byte, "big")) #endianness doesn't matter 
    output_file.write(x   " "   x   " "   x   " \n")
    pixels_written = pixels_written   1
    byte = input_file.read(1) #get next byte

while pixels_written < (height * width): #finish up the grid
    output_file.write("0  0  0 \n")
    pixels_written = pixels_written   1

CodePudding user response:

Here is the code that do the job. Remember to put ".png" to the output file name.

import os
import imageio
import array
import numpy as np

f = open(input_filename, 'rb')
ln = os.path.getsize(input_filename)  # length of file in bytes
if width == 0:
    width = ln
rem = ln % width
a = array.array("B")  # uint8 array
a.fromfile(f, ln - rem)
f.close()
g = np.reshape(a, (len(a) // width, width))
g = np.uint8(g)
imageio.imwrite(output_filename, g)  # save the image
  •  Tags:  
  • Related