base64

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Jay

    #1

    base64

    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()

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

  • John Machin

    #2
    Re: base64

    On 13/04/2006 4:07 AM, Jay wrote:[color=blue]
    > I have bean trying to get my head around reading .GIF files from base64
    > strings,[/color]

    FROM base64? Sounds a tad implausible.
    [color=blue]
    > Basically I need to specify a filename and convert it to base64 then I
    > can copy/past the string to wear I want it.[/color]

    TO base64? That's better, provided the referent of the first "it" is the
    file contents, not the filename.
    [color=blue]
    > 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[/color]

    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]
    [color=blue]
    >
    > def Encode(self,eve nt):
    > '''
    > Take's the string from (self.FileInput Line),
    > converts it to base64 then desplays it in (self.DisplayTe xt)
    > '''[/color]

    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
    [color=blue]
    > self.DisplayTex t.insert(END, "...No Sutch File...")[/color]

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

    HTH,
    John

    Comment

    • Fredrik Lundh

      #3
      Re: base64

      John Machin wrote:
      [color=blue]
      > *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 /.../[/color]

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

      </F>



      Comment

      • John Machin

        #4
        Re: base64

        On 13/04/2006 7:22 AM, Fredrik Lundh wrote:[color=blue]
        > John Machin wrote:
        >[color=green]
        >> *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 /.../[/color]
        >
        > base64.encodest ring(data) does all that in one step, of course.
        >[/color]

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

        Comment

        • Fredrik Lundh

          #5
          Re: base64

          John Machin wrote:
          [color=blue][color=green]
          > > base64.encodest ring(data) does all that in one step, of course.[/color]
          >
          > and it's tagged as part of the "legacy interface", and gives no control
          > over the chuck size, of course :-)[/color]

          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>



          Comment

          • Jay

            #6
            Re: base64

            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()

            Comment

            Working...