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)
Additionally, you need to register the PNG image format handler before calling image.DecodeConfig(). This can be achieved using:
import _ "image/png"
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) }
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!