Hexadecimal to Image Conversion

Question:

I am converting the hexadecimal files to images. The input files are converted to byte string using binascii library. The problem arises when the byte string is written to form an image. The output of all the hexadecimal files is same. I will be grateful if someone provides me a solution.

Here is my code:

import binascii
import cv2
import os
from tkinter import *
from tkinter import filedialog

#Hide the root window that comes by default
root=Tk()
root.withdraw()

#Browse and select txt files
dir=[]
dir=filedialog.askopenfilenames(
        initialdir="C:BinariesHexadecimal_Text_Files", 
        title="Open Text file", 
        filetypes=(("Text Files", "*.txt"),)
        )

#Reading data in txt files and decoding hexadecimal characters
for x in dir:
        tf=open(x)#Open file    
        data=tf.read()#Read data in file
        data=data.replace(' ','')#Remove whitespaces
        data=data.replace('n','')#Remove breaks in lines
        data=binascii.a2b_hex(data)
        tf.close()

#Extract txt filename without extension
        pathname, extension = os.path.splitext(f"{x}")#Split path into filename and extenion
        filename = pathname.split('/')#Get filename without txt extension
        filepath=f"C:BinariesImages{filename[-1]}.png"#Defining name of image file same as txt file

#Write data into image
        with open(filepath, 'wb') as image_file:
                img=image_file.write(data)
    
#Resizing Image
        img=cv2.resize(img,(500,500))
        cv2.imwrite(filepath,img)  
          

Output:

enter link description here

Asked By: Salaar Imran

||

Answers:

I made my own version because I could not get yours to work, but if you want to make yours work, at least one problem with I found is with this line:

img=cv2.resize(img,(500,500))      

by printing all the variables after the supposed "conversion", I found that your variable img in the previous line is not an image but the result of image_file.write(data) which returns the number of bytes written to the file and not the image itself, which is probably why it always prints the same image.

Here is my version

root=Tk()
root.withdraw()

file_path = filedialog.askopenfilename(
    initialdir = "C:BinariesImages", 
    title = "Select Hexadecimal Text File", 
    filetypes = (("Text Files", "*.txt"),)
)

with open(file_path, "r") as hex_file:
    hex_data = hex_file.read().replace("n", "")
    #replaces white spaces and new lines from file
    binary_data = binascii.a2b_hex(hex_data)
    #converts the hexadecimal data to binary

pathname, extension = os.path.splitext(file_path)
image_path = pathname + ".png"
#image path and format 

with open(image_path, "wb") as image_file:
    image_file.write(binary_data)
    #writing the binary data to image file

img = cv2.imread(image_path, cv2.IMREAD_UNCHANGED)

#if txt file is empty
if img is None:
    print("Error: Image not loaded!")
else:
    cv2.imshow("image", img)
    #waits for key input and closes when pressing any key
    cv2.waitKey(0)
    cv2.destroyAllWindows()
Answered By: Ietu

I have converted the hexadecimal files into images by using numpy array and Pillow. Now I am getting different images.

import numpy as np
import binascii
import os
from PIL import Image as im
from tkinter import *
from tkinter import filedialog

# Hide the root window that comes by default
root = Tk()
root.withdraw()

# Browse and select txt files
dir = []
dir = filedialog.askopenfilenames(
initialdir="C:BinariesFolder_3",
title="Open Text file",
filetypes=(("Text Files", "*.txt"),)
)

# Reading data in txt files and decoding hexadecimal characters
for temp in dir:
    tf = open(temp)  # Open file
    data = tf.read()  # Read data in file
    data= data.replace(''','')   #Remove label
    data = data.replace(' ', '')  # Remove whitespaces
    data = data.replace('n', '') # Remove breaks in lines
    data = binascii.a2b_hex(data)
    tf.close()
           
#Converting bytes array to numpy array
    a = np.frombuffer(data, dtype='uint8')
    #print(a) //Display array

#Finding optimal factor pair for size of image    
    x = len(a)
    val1=0
    val2=0
    for i in range(1, int(pow(x, 1 / 2))+1):
        if x % i == 0:
                val1=i
                val2=int(x / i)

#Converting 1-D to 2-D numpy array                
    a = np.reshape(a, (val1, val2))
    #print(a) #Display 2-D array

#Writing array to image
    data = im.fromarray(a)

# Split path into filename and extenion
    pathname, extension = os.path.splitext(f"{temp}")
    filename = pathname.split('/')  # Get filename without txt extension

# Defining name of image file same as txt file
    filepath = f"C:BinariesImages_3{filename[-1]}.png"

#Resize image    
    data=data.resize((500,500))
    
#Saving image into path    
    data.save(filepath)

enter image description here

enter image description here

Answered By: Salaar Imran
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.