I am getting: error: illegal base64 data at input byte 4
When passing in Base64Image into base64.StdEncoding.DecodeString(str)
:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYA...
Let me know if you need the full base64, I have just pasted in the first part as it looks like the problem is within 4 byte?
data, errBase := base64.StdEncoding.DecodeString(Base64Image)
if errBase != nil {
fmt.Println("error:", errBase)
return false
}
Do you know why?
Also this may happen if you encoded using StdEncoding
and trying to decode using RawStdEncoding
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:
data:[<MIME-type>][;charset=<encoding>][;base64],<data>
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:]
fmt.Println(b64data)
Output:
iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYA
Of 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.
Sometimes this happens if your base64 string is not properly padded with == at the end.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With