0

I'm trying to extract the binary information from an image (like \ xff), and save it into a text file. Ultimately, I should also be able to reverse the effect, and generate an image from the text file.

I'm using the code below to try to create the text file; it does not throw an error, but the text generated does not generate an image. Here is an example of the contents of one of the text files created by this code.

file = open(image, "rb")
data = file.read()
file.close()


file = open(txt file, "w")
file.write(str(data))
file.close()
Nat Riddle
  • 928
  • 1
  • 10
  • 24
bob
  • 11

1 Answers1

1

You should read/write your files on binary mode with "rb" and "wb" attributes on open() function:

Try this:

with open(image1, "rb") as input_file:
    data = input_file.read()

with open(image2, "wb") as output_file:
    output_file.write(data)

But if you want to convert your target file bytes to bits (01) and save them and reverse this job again you can simply use numpy package:

Try This:

import numpy as np

Bytes = np.fromfile("image1.png", dtype="uint8")
Bits = np.unpackbits(Bytes)


with open("bits.txt", "w") as export_bits:
    export_bits.write("".join(list(map(str, Bits))))

with open("bits.txt", "r") as load_bits:
    string_bits_data = list(map(int, load_bits.read()))


save_new_image = np.packbits(string_bits_data).astype('int8').tofile("image2.png")
print("Done")

Credits to mikhail-v (UID: 4157407) from: Convert bytes to bits in python.

DRPK
  • 2,023
  • 1
  • 14
  • 27