Base64 Decoding Error: "Illegal Base64 Data at Input Byte 4"
When attempting to decode a Base64-encoded string using base64.StdEncoding.DecodeString(str), you may encounter the error: "illegal base64 data at input byte 4." This error indicates that the provided input is not in a valid Base64 format.
The issue in your case lies not in the Base64 encoding itself, but in the input string. Instead of a pure Base64 string, you are trying to decode a Data URI scheme.
A Data URI scheme represents data within a web page as inline content, following this format:
data:[
In your case, the input is a Data URI scheme containing an image/png MIME type and Base64-encoded data. To decode it, you first need to extract the Base64 portion.
input := "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYA" b64data := input[strings.IndexByte(input, ',')+1:] fmt.Println(b64data)
Output:
iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYA
Now you can decode the extracted Base64 string:
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]
By extracting the Base64 data from the Data URI scheme and performing the decoding process, you can successfully decode the Base64-encoded content.
The above is the detailed content of Why Am I Getting a 'Illegal Base64 Data at Input Byte 4' Error When Decoding a Data URI?. For more information, please follow other related articles on the PHP Chinese website!