Home >Backend Development >Golang >Why Does base64.StdEncoding.DecodeString(str) Fail with 'illegal base64 data at input byte 4' Error?
When attempting to decode a Base64Image using base64.StdEncoding.DecodeString(str), users may encounter the error "illegal base64 data at input byte 4." This occurs because the input string is not entirely Base64 encoded.
The input provided is a Data URI scheme, a format used to embed data, such as images, within web pages. It follows this structure:
data:[<MIME-type>][;charset=<encoding>][;base64],<data>
In the given example, the MIME-type is "image/png," and ";base64" indicates that the data component is Base64 encoded.
To extract the Base64 encoded data, remove the prefix up to and including the comma:
input := "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYA" b64data := input[strings.IndexByte(input, ',')+1:]
Now, you can decode the Base64 string:
data, err := base64.StdEncoding.DecodeString(b64data) if err != nil { fmt.Println("error:", err) }
This process will successfully decode the image data without encountering the "illegal base64 data at input byte 4" error.
The above is the detailed content of Why Does base64.StdEncoding.DecodeString(str) Fail with 'illegal base64 data at input byte 4' Error?. For more information, please follow other related articles on the PHP Chinese website!