473,725 Members | 2,053 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

base64

Jay
I have bean trying to get my head around reading .GIF files from base64
strings,
Basically I need to specify a filename and convert it to base64 then I
can copy/past the string to wear I want it.
Cold somebody check this for me to see what I have done wrong:

If you run this program and enter a path for a .GIF file into the white
box and hit <Enter> it should display the string in the blue box.

To test this if you click the menu File Display it will create a top
level window displaying the image and giving the original string
underneath.

The bit I can not understand:

It will generate the base64 string but when trying to display it, it
reads the string up until the first ("/n") ("Cg==") <Return>
and then stops.

The base 64 string seams to be complete but when converted back it is
incomplete.

Thanks

Jay Dee

............... .........START. ............... ......

from Tkinter import *
from base64 import *

############### ############### ############### ############### ############### #
############### ############### ############### ############### ############### #
# Module: Base64 Encoder / Decoder.py
# Author: Jay Dee
# Date: 08/04/2006
# Version: Draft 0.1
# Coments: A Base64 Encoder / Decoder for converting files into Base64
strings
############### ############### ############### ############### ############### #
############### ############### ############### ############### ############### #

class App:
def __init__(self, root):
root.title("Bas e64 Encoder / Decoder")
############### ############### ############### ############### ############### #
# Menu Bar
############### ############### ############### ############### ############### #
self.menubar = Menu(root)
# create a pulldown menu, and add it to the menu bar
self.filemenu = Menu(self.menub ar, tearoff=0)
self.filemenu.a dd_command(labe l="Display!",
command=self.Di splay)
self.filemenu.a dd_separator()
self.filemenu.a dd_command(labe l="Quit!", command=root.qu it)
self.menubar.ad d_cascade(label ="File", menu=self.filem enu)
# display the menu
root.config(men u=self.menubar)
############### ############### ############### ############### ############### #
# Main
############### ############### ############### ############### ############### #
# File Input
self.FileInputF rame = Frame(root)
self.FileInputF rame.pack(side= TOP, fill=X)

self.FileInputL ine = Entry(self.File InputFrame,
bg="white",
width=70)
self.FileInputL ine.pack(side=L EFT, fill=X, expand=1)
# Display Area
self.DisplayFra me = Frame(root)
self.DisplayFra me.pack(side=TO P, fill=BOTH, expand=1)

self.DisplayTex t = Text(self.Displ ayFrame,
bg="lightblue" ,
width=95,
height=40)
self.DisplayTex t.pack(side=LEF T, fill=BOTH, expand=1)

root.bind("<Ret urn>",self.Enco de)

def Encode(self,eve nt):
'''
Take's the string from (self.FileInput Line),
converts it to base64 then desplays it in (self.DisplayTe xt)
'''
self.DisplayTex t.delete(1.0,EN D)

info = self.FileInputL ine.get()
if info == "":
self.DisplayTex t.insert(END, "...Empty String...")
else:
try:
file = open(info)
try:
while 1:
line = file.readline()
if not line:
break
Encode = b64encode(line)
self.DisplayTex t.insert(END, Encode)
except:
self.DisplayTex t.insert(END, "...Data Problem...")

except:
self.DisplayTex t.insert(END, "...No Sutch File...")

def Display(self):
'''
Take's the string from (self.DisplayTe xt), Creats a topleval
frame and displays the Data
'''
info = self.DisplayTex t.get(1.0,END)
# Display as Image
try:
self.DisplayIma ge = Toplevel()

self.InfoDispla y = PhotoImage(data =info)
PhotoSize =
[self.InfoDispla y.width(),self. InfoDisplay.hei ght()]

self.DisplayIma geCanvas = Canvas(
self.DisplayIma ge,
width=150,
height=PhotoSiz e[1] + 15)
self.DisplayIma geCanvas.pack(f ill=BOTH, expand=1)
self.InfoDispla y2 = self.DisplayIma geCanvas.create _image(
PhotoSize[0] / 2 + 10,
PhotoSize[1] / 2 + 10,
image=self.Info Display)
self.InfoDispla y2 = self.DisplayIma geCanvas
except:pass
# Display as Text
self.DisplayIma geText = Text(
self.DisplayIma ge,
width=70,
height=30)
self.DisplayIma geText.pack(fil l=BOTH, expand=1)

Decode = b64decode(info)
self.DisplayIma geText.insert(E ND, Decode)
root = Tk()
app = App(root)
root.mainloop()

############### ############### ############### ############### ############### ##

Apr 12 '06 #1
5 4117
On 13/04/2006 4:07 AM, Jay wrote:
I have bean trying to get my head around reading .GIF files from base64
strings,
FROM base64? Sounds a tad implausible.
Basically I need to specify a filename and convert it to base64 then I
can copy/past the string to wear I want it.
TO base64? That's better, provided the referent of the first "it" is the
file contents, not the filename.
Cold somebody check this for me to see what I have done wrong:
The bit I can not understand:

It will generate the base64 string
No it doesn't and no it can't; it's reading the *FILE* one "line" at a
time. This is in fact the root cause of your problem; a GIF file is a
binary file; there are no "lines"; any '\n' or '\r' characters are
binary data. Why is it stopping early? Possibly there is a ctrl-Z
character in the file and you are running on Windows. You need to open
the file with "rb" as the second arg, and read the whole file in as one
string. *After* encoding it, you can break up the base64 string into
bite-size chunks, append a newline (that's "\n", NOT "/n") to each
chunk, and send it over a 7-bit-wide channel.

You may wish to try a small console script that might help you
understand what's going on:

# Input: name of file as 1st arg
# Output: base64 encoding written to stdout in 64-byte chunks
import sys, base64
CHUNKSIZE = 64
fname = sys.argv[1]
fhandle = open(fname, "rb")
fcontents = fhandle.read()
b64 = base64.b64encod e(fcontents)
for pos in xrange(0, len(b64), CHUNKSIZE):
print b64[pos:pos+CHUNKSI ZE]

[snip]

def Encode(self,eve nt):
'''
Take's the string from (self.FileInput Line),
converts it to base64 then desplays it in (self.DisplayTe xt)
'''
The above documentation reflects neither what the method is doing now
nor what it should be doing. The latter is something like:

Takes (LTFA!) a filename from self.FileInputL ine
Opens the file in binary mode
Encodes the file's contents as base64
Displays the encoded string in self.DisplayTex t
self.DisplayTex t.insert(END, "...No Sutch File...")


Is the GIF file meant to be a photo of the late Screaming Lord?

HTH,
John
Apr 12 '06 #2
John Machin wrote:
*After* encoding it, you can break up the base64 string into
bite-size chunks, append a newline (that's "\n", NOT "/n") to each
chunk /.../


base64.encodest ring(data) does all that in one step, of course.

</F>

Apr 12 '06 #3
On 13/04/2006 7:22 AM, Fredrik Lundh wrote:
John Machin wrote:
*After* encoding it, you can break up the base64 string into
bite-size chunks, append a newline (that's "\n", NOT "/n") to each
chunk /.../


base64.encodest ring(data) does all that in one step, of course.


and it's tagged as part of the "legacy interface", and gives no control
over the chuck size, of course :-)
Apr 12 '06 #4
John Machin wrote:
base64.encodest ring(data) does all that in one step, of course.


and it's tagged as part of the "legacy interface", and gives no control
over the chuck size, of course :-)


if you read the documentation, it's clear that legacy means "base64 only",
not "deprecated ". it uses the chunk size specified by the MIME standard,
which is the traditional Base64 reference.

it's not like Base16 and Base32 are new things that will soon overtake the
old and little used Base64-according-to-MIME encoding...

</F>

Apr 13 '06 #5
Jay
I don't know whether it is right yet but it dues what I wanted it to
do now so thank you all,

Oh and sorry for my bad grammar.

One last thing though is that I would like to be able to split the
string up into lines of 89 carictors, I have lookd through the split
methods and all I can find is splitting up words and splitting at a
pacific caricature, I can not see how you split after a number of
caricatures
............... .........START. ............... ......

from Tkinter import *
from base64 import *

############### ############### ############### ############### #########
############### ############### ############### ############### #########
# Module: Base64 Encoder / Decoder.py
# Author: Jay Dee
# Date: 08/04/2006
# Version: Draft 0.1
# Coments: A Base64 Encoder / Decoder for converting files into Base64
strings
############### ############### ############### ############### #########
############### ############### ############### ############### #########

class App:
def __init__(self, root):
root.title("Bas e64 Encoder / Decoder")
############### ############### ############### ############### #########
# Menu Bar
############### ############### ############### ############### #########
self.menubar = Menu(root)
# create a pulldown menu, and add it to the menu bar
self.filemenu = Menu(self.menub ar, tearoff=0)
self.filemenu.a dd_command(labe l="Display!",
command=self.Di splay)
self.filemenu.a dd_separator()
self.filemenu.a dd_command(labe l="Quit!", command=root.qu it)
self.menubar.ad d_cascade(label ="File", menu=self.filem enu)
# display the menu
root.config(men u=self.menubar)
############### ############### ############### ############### #########
# Display B64 Text
############### ############### ############### ############### #########
# File Input
self.FileInputF rame = Frame(root)
self.FileInputF rame.pack(side= TOP, fill=X)

self.FileInputL ine = Entry(self.File InputFrame,
bg="white",
width=70)
self.FileInputL ine.pack(side=L EFT, fill=X, expand=1)
# Display Area
self.DisplayFra me = Frame(root)
self.DisplayFra me.pack(side=TO P, fill=BOTH, expand=1)

self.DisplayTex t = Text(self.Displ ayFrame,
bg="lightblue" ,
width=95,
height=40)
self.DisplayTex t.pack(side=LEF T, fill=BOTH, expand=1)

root.bind("<Ret urn>",self.Enco de)

def Encode(self,eve nt):
'''
Take's the file name from (self.FileInput Line),
opens file,
converts it to base64 then desplays it in (self.DisplayTe xt)
'''
self.DisplayTex t.delete(1.0,EN D)

info = self.FileInputL ine.get()
if info == "":
self.DisplayTex t.insert(END, "...Please enter file...")
else:
try:
file = open(info,"rb")
try:
Data = file.read()
Encode = b64encode(Data)
Encode = Encode.split()
self.DisplayTex t.insert(END, Encode)
except:
self.DisplayTex t.insert(END, "...Data Erra...")

except:
self.DisplayTex t.insert(END, "...No Sutch File...")

def Display(self):
'''
Take's the string from (self.DisplayTe xt), Creats a topleval
frame and displays the Data as an image,if that fales it
displays it as text.
'''
info = self.DisplayTex t.get(1.0,END)
# Display as Image
try:
self.DisplayIma ge = Toplevel()

self.InfoDispla y = PhotoImage(data =info)
PhotoSize =
[self.InfoDispla y.width(),self. InfoDisplay.hei ght()]

self.DisplayIma geCanvas = Canvas(
self.DisplayIma ge,
width=150,
height=PhotoSiz e[1] + 15)
self.DisplayIma geCanvas.pack(f ill=BOTH, expand=1)
self.InfoDispla y2 = self.DisplayIma geCanvas.create _image(
PhotoSize[0] / 2 + 10,
PhotoSize[1] / 2 + 10,
image=self.Info Display)
self.InfoDispla y2 = self.DisplayIma geCanvas

# Display as Text
except:
self.DisplayBas e64Text = Text(
self.DisplayIma ge,
width=70,
height=30)
self.DisplayBas e64Text.pack(fi ll=BOTH, expand=1)

Decode = b64decode(info)
self.DisplayIma geText.insert(E ND, Decode)
root = Tk()
app = App(root)
root.mainloop()

Apr 13 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
2565
by: Karl Pech | last post by:
Hi all, I'm trying to write a program which can read in files in the following format: sos_encoded.txt: --- begin-base64 644 sos.txt UGxlYXNlLCBoZWxwIG1lIQ== ---
27
15047
by: gRizwan | last post by:
Hello all, We have a problem on a webpage. That page is sent some email data in base64 format. what we need to do is, decode the base64 data back to original shape and extract attached image from it. Any help will be highly appriciated. Thanks
4
5361
by: John | last post by:
Hi all, I've been going through google and yahoo looking for a certain base64 decoder in C without success. What I'm after is something that you can pass a base64 encoded string into and get back a decoded String. Any help is very much appreciated. Thanks Philip.
0
3158
by: Phil C. | last post by:
(Cross post from framework.aspnet.security) Hi. I testing some asp.net code that generates a 256 bit Aes Symmetric Key and a 256 bit entropy value. I encrypt the Aes key(without storing it as Base64) with the host's dpapi using the entropy value(without storing it as Base64), and then store the encrypted Aes key value and the entropy value in some SHARED VARIABLES AS BYTE ARRAYS(not Base64). I then decrypt the stored encrypted Aes...
7
7953
by: Neo Geshel | last post by:
Greetings. I have managed to stitch together an awesome method of posting text along with an image to a database, in a way that allows an unlimited number of previews to ensure that text and image are perfect before submission. This involves converting any uploaded image to a Base64 String and holding that in a hidden form field until either the post gets submitted to the database or the image gets replaced with another one. I...
4
5541
by: Russell Warren | last post by:
I've got a case where I want to convert binary blocks of data (various ctypes objects) to base64 strings. The conversion calls in the base64 module expect strings as input, so right now I'm converting the binary blocks to strings first, then converting the resulting string to base64. This seems highly inefficient and I'd like to just go straight from binary to a base64 string. Here is the conversion we're using from object to...
1
3882
by: Roland Rickborn | last post by:
Hallo zusammen, in meine Anwendung ist ein Bild eingebettet und oben in der Leiste soll ein Icon erscheinen. Ausserdem will ich nur _eine_ Datei ausgeben, also ohne zusärtliche Bild-Dateien etc. Dazu habe ich das Bild in base64 codiert und als String im Skript gespeichert, siehe unten. Beim Ausführen des Skripts wird dieser String decodiert, in ein Image umgewandelt und als Bitmap dargestellt.
13
14786
by: aruna.eies.eng | last post by:
i am currently trying to convert data into binary data.for that i need to know how to achieve it in c language and what are the libraries that we can use. so if any one can send me a sample code or send me the library file which helps that is really grateful. aruna.
10
4051
by: pycraze | last post by:
Hi , I am currently trying to implement base64 encoding and decoding scheme in C . Python has a module , base64 , that will do the encoding and decoding with ease . I am aware of OpenSSL having support for base64 encoding and decoding , but i will have to now implement both in C without using the openssl libraries . I was able to download a code w.r.t. base 64 encoding and decoding . I am attaching the code below .
0
9257
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9174
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9111
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8096
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6702
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6011
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4782
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3221
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2634
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.