Home > Backend Development > Golang > Why Does base64.StdEncoding.DecodeString(str) Fail with 'illegal base64 data at input byte 4' Error?

Why Does base64.StdEncoding.DecodeString(str) Fail with 'illegal base64 data at input byte 4' Error?

Patricia Arquette
Release: 2024-12-02 22:15:19
Original
210 people have browsed it

Why Does base64.StdEncoding.DecodeString(str) Fail with

"Illegal base64 data at input byte 4" When Using base64.StdEncoding.DecodeString(str)

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>
Copy after login

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:]
Copy after login

Now, you can decode the Base64 string:

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

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template