Sunday, July 24, 2022

Converting image to text, saving to disk, reading text from disk and displaying image


A brief introduction of 'base64' functions 'b64encode' and 'b64decode':

(base) C:\Users\Ashish Jain>python
Python 3.7.1 (default, Dec 10 2018, 22:54:23) [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from base64 import b64encode as b, b64decode as d
>>> s = 'hello'
>>> b(bytes(s, 'utf-8'))
b'aGVsbG8='
>>> bs = b(bytes(s, 'utf-8'))
>>> d(bs)
b'hello'
>>> d(b'aGVsbG8=')
b'hello'
>>> d(bs).decode("utf-8") 
'hello'

Now with image:

from base64 import b64decode, b64encode
image_handle = open('test_image.png', 'rb')
raw_image_data = image_handle.read()
encoded_data = b64encode(raw_image_data)

with open('i.txt', 'wb') as f:
  f.write(encoded_data)

with open('i.txt', 'rb') as f:
  b = f.read()

print(type(b)) 
[class 'bytes'] 
print(encoded_data == b) 
True 
with open('i.png', 'wb') as f:
  f.write(b64decode(b)) 

If you have a text file and it has data such as this: b'iVB...ggg=='
That means you had called str() function on 'bytes' type data and saved that string.

If you have a text file that has data such as this: iVB...ggg==
Then, you can read this file as ">>> with open('img.txt', 'rb') as f:" to get a 'bytes' type data. 
Tags: Technology,Python,

No comments:

Post a Comment