Home > Backend Development > Golang > How to Properly Decode Base64 Encoded Images in Go?

How to Properly Decode Base64 Encoded Images in Go?

Linda Hamilton
Release: 2024-12-04 11:55:11
Original
974 people have browsed it

How to Properly Decode Base64 Encoded Images in Go?

Decoding Base64 Encoded Images in Go

When working with canvas, it's possible to obtain a base64 image data URL. However, when attempting to decode this image using image.DecodeConfig(), you may encounter the error "Unknown image format."

This issue arises because the data URL contains additional information beyond the base64-encoded image data. To correctly decode the image, you need to remove the prefix:

// Remove the data URL prefix
input := strings.Replace(req.PostFormValue("dataurl"), "data:image/png;base64,", "", 1)
Copy after login

Additionally, you need to register the PNG image format handler before calling image.DecodeConfig(). This can be achieved using:

import _ "image/png"
Copy after login

Alternatively, you can directly use png.DecodeConfig() if you know the exact image format.

Example:

import _ "image/png"

reader := base64.NewDecoder(base64.StdEncoding, strings.NewReader(input))
imageConfig, _, err := image.DecodeConfig(reader)
if err != nil {
    log.Fatal(err)
}
Copy after login

By following these steps, you can successfully decode base64-encoded images and obtain their width and height.

The above is the detailed content of How to Properly Decode Base64 Encoded Images in Go?. 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