Invalid base64 data on input byte 4 when using base64.StdEncoding.DecodeString (str)

I am getting: error: illegal base64 data at input byte 4

When passing Base64Image to base64.StdEncoding.DecodeString(str)

:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYA... 

      

Let me know if you want the full base64, I just pasted the first part in, so it looks like the problem is 4 bytes?

data, errBase := base64.StdEncoding.DecodeString(Base64Image)
if errBase != nil {
    fmt.Println("error:", errBase)
    return false
}

      

You know why?

+5


source to share


3 answers


Not all of your input string you are trying to decode is Base64 encoded.

You have a data URI scheme that provides a way to include data in a string in web pages as if it were external resources.

It has the format:

data:[<MIME-type>][;charset=<encoding>][;base64],<data>

      

Where in your case image/png

is the MIME type, there is no optional encoding, and ";base64"

is a constant string indicating what <data>

is encoded using Base64 encoding.

To get the data (i.e. Base64 encoding), disable the prefix before the comma (including the comma):

input := "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYA"

b64data := input[strings.IndexByte(input, ',')+1:]
fmt.Println(b64data)

      



Output:

iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYA

      

From which you can now decode:

data, err := base64.StdEncoding.DecodeString(b64data)
if err != nil {
    fmt.Println("error:", err)
}
fmt.Println(data)

      

Output:

[137 80 78 71 13 10 26 10 0 0 0 13 73 72 68 82 0 0 0 100 0 0 0 100 8 6 0]

      

Try it on the Go Playground .

+12


source


This is because your string is not in base64 until the data is comma: image / png; base64, iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYA ...

import "strings" and use split to get the half after the decimal point and then call decodestring with that.



import "strings"

data, errBase := base64.StdEncoding.DecodeString(strings.Split(Base64Image, "base64,")[1]))
if errBase != nil {
    fmt.Println("error:", errBase)
    return false
}

      

EDIT: Made a split token base64,

because it's more specific to your input.

+2


source


This sometimes happens if your base64 string is incorrectly filled with == at the end.

+2


source







All Articles