0

I am working on a chat room that can send images. But the images are large so I send them in part and add each part to a string. And when i try to decode the string that has the information in it I get this error:

return binascii.a2b_base64(s)
Error: Incorrect padding

Here is my code:

def getData(self):
    chatArea = self.chatArea

    imageBytes = ""
    imageMode = False

    while 1:
        data = self.s.recv(8000)
        if not data:
            break

        if imageMode == True:
            imageBytes = imageBytes + data

            if data[-1] == ")":
                newImage = open("Untitled.png", "wb")
                newImage.write(imageBytes.decode("base64"))
                newImage.close()
                imageMode = False
                print("Done")
        else:
            if re.findall(r'\[(.*?)\]', data) == ["Image"]:
                print("Got the data")
                imageMode = True
            else:
                string = data + "\n\n"
                chatArea.configure(state=NORMAL)
                chatArea.insert(END, string)
                chatArea.configure(state=DISABLED)

                newString = string.split(":")[0]

                self.chatArea.see(END)

        if newString == self.myName or newString == "Server":
            pass
        else:
            winsound.PlaySound("Notify.wav", winsound.SND_FILENAME)

Why am i getting this error when i try to create the image? How can I fix it?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
  • @howaboutNO I am not trying to ignore the error I am trying to find a way to prevent the error. And why it is giving me the error. –  Jan 12 '15 at 03:39
  • Does anyone have a solution? –  Jan 12 '15 at 03:54
  • 1
    Base64 requires padding when the encoded characters are not a multiple of 4. – Mark Ransom Jan 12 '15 at 04:05
  • Unlike forum sites, we don't use "Thanks", or "Any help appreciated", or signatures on [so]. See "[Should 'Hi', 'thanks,' taglines, and salutations be removed from posts?](http://meta.stackexchange.com/questions/2950/should-hi-thanks-taglines-and-salutations-be-removed-from-posts). BTW, it's "Thanks in advance", not "Thanks in advanced". – John Saunders Jan 17 '15 at 05:54

1 Answers1

0

if data[-1] == ")": seems to expect that the base64 encoded string ends with a close bracket.

This is possibly the cause of your problem. Does the imageBytes data have trailing or leading protocol data that you need to trim.

Hope this helps.

Joe
  • 1,479
  • 13
  • 22
  • Yes I added a ) to the end of the string. Will this cause errors? –  Jan 12 '15 at 04:02
  • Yeah, I think so, If memory serves you can chuck white-space into base64 encoded data but very little else. try `imageBytes = imageBytes.rstrip( ")" )` – Joe Jan 12 '15 at 04:05