Reputation: 393
So i am working on a project where I am taking apart an image into a string, adding to said string, then decoding it back into an image, but I find that when I encode it after the program has run, all added code has been disregarded. Is this a programming problem on my end, or does encoding disregard data that's not required for the image?
Lets dive deeper:
Throughout my code I watch to make sure that the contents going into the final decode is what I want it to be, and it is. Do that narrows it down to the actually decoding process which must affect it. When the new image is reopened, the new text is gone.
Is there a way to fix this?
import base64
import os
import random
with open("wow.png", "rb") as imageFile: #image to bytes
string = base64.b64encode(imageFile.read())
print(type(string))
print(string)
betterString = string.decode("utf-8") #bytes to string
print(type(betterString))
print(betterString)
betterString = betterString + "I Love you."
back2String = betterString.encode("utf-8") #String to bytes
print(type(back2String))
print(back2String)
fh = open("wow.png", "wb")
decstr=base64.b64decode(back2String)
fh.write(decstr)
fh.close()
As previously said, the new image should have the entirety of the saved contents, but in reality it is only a portion which was the original imported file.
Upvotes: 0
Views: 1546
Reputation: 10030
PNG crops everything after the trailing ==
. You should add your strings not in the end of the file, but just before ==
. Here is the working line you should replace:
betterString = betterString[:-2] + "I Love youWAKAWAKAWAKA" + "=="
base64 encoding uses [a-zA-z0-9+/=]
symbols, you can't use whitespaces, points etc. in your strings, it will disappear automatically.
Edit 1: After you changed your question, I should add that you should not open your file again while it is opened. Open and write into the another file, as there was in the first version of your question.
Upvotes: 2
Reputation: 140
It seems odd to me that inside the with
statement you open the image again fh = open("wow.png", "wb"))
What about just calling imageFile.write(decstr)
instead?
N.B. I cant comment as not enough reputation yet
Upvotes: 2