base64

John Machin sjmachin at lexicon.net
Wed Apr 12 16:58:31 EDT 2006


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.b64encode(fcontents)
for pos in xrange(0, len(b64), CHUNKSIZE):
     print b64[pos:pos+CHUNKSIZE]

[snip]

> 
>     def Encode(self,event):
>         '''
>         Take's the string from (self.FileInputLine),
>         converts it to base64 then desplays it in (self.DisplayText)
>         '''

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.FileInputLine
Opens the file in binary mode
Encodes the file's contents as base64
Displays the encoded string in self.DisplayText

>                 self.DisplayText.insert(END, "...No Sutch File...")

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

HTH,
John



More information about the Python-list mailing list