Illegal base64 data at input byte 4 when using base64.StdEncoding.DecodeString(str)

Not all of your input string you try to decode is Base64 encoded form.

What you have is a Data URI scheme, that provides a way to include data in-line in web pages as if they were external resources.

It has a format of:


Where in your case image/png is the MIME-type, the optional charset is missing, and ";base64" is a constant string indicating that <data> is encoded using Base64 encoding.

To acquire the data (that is the Base64 encoded form), cut off the prefix up to the comma (comma included):

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

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



Of which you can now decode:

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


[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.

It's because your string isn't in base64 until after the comma data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYA...

import "strings" and use split to get the half after the comma 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 the split token base64, because it's more specific to your input.

Sometimes this happens if your base64 string is not properly padded with == at the end.