Decoding Go Base64 Image Data
Problem:
You're receiving a Base64-encoded image data URL from a canvas and trying to decode it to retrieve its width and height, but you're encountering an "Unknown image format" error.
Solution:
The provided data URL format is a Data URI scheme, which includes additional information like the image type and Base64 encoding. To decode it properly, follow these steps:
import ( "encoding/base64" "fmt" "image" _ "image/png" // Register the PNG format handler "strings" ) func decodeBase64Image(dataURL string) (image.Config, error) { // Remove the prefix (e.g., "data:image/png;base64,") base64Data := dataURL[strings.IndexByte(dataURL, ',')+1:] // Decode the Base64-encoded image data decoded, err := base64.StdEncoding.DecodeString(base64Data) if err != nil { return image.Config{}, fmt.Errorf("could not decode Base64 data: %w", err) } // Decode the image configuration return image.DecodeConfig(bytes.NewReader(decoded)) }
By registering the PNG format handler (_ "image/png"), you enable the image.DecodeConfig() function to properly decode the image data. You can also use the png.DecodeConfig() function directly if you know the image format.
Avoidance of Prefix Replacement:
Instead of replacing the prefix with an empty string, slice the input string to extract the Base64-encoded data. This is a more efficient approach as it doesn't require copying the entire string in memory.
base64Data := input[strings.IndexByte(input, ',')+1:]
The above is the detailed content of How to Decode Base64-Encoded Image Data and Retrieve Its Dimensions in Go?. For more information, please follow other related articles on the PHP Chinese website!