Last active
March 18, 2022 05:34
-
-
Save younisshah/89d481b184c2d721ab99ae9b7db2857e to your computer and use it in GitHub Desktop.
Save a Base64 Image to disk (PNG and JPEG formats only)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package galileo_gists | |
import ( | |
"strings" | |
"time" | |
"math/rand" | |
"os" | |
"encoding/base64" | |
"image" | |
"image/png" | |
"image/jpeg" | |
) | |
const ( | |
FS_PATH = "/fs_path/" | |
CHARS = "abcdefghijklmnopqrstuvwxyz0123456789" | |
) | |
func SaveBase64ImageToDisk(prefix, imageString string) (interface{}, error) { | |
imageExt := strings.ToLower(strings.Split(strings.Split(imageString, ";")[0], "/")[1]) | |
imageData := strings.Split(imageString, ";base64,")[1] | |
imageReader := base64.NewDecoder(base64.StdEncoding, strings.NewReader(imageData)) | |
if decodedImage, _, err := image.Decode(imageReader); err != nil { | |
return nil, err | |
} else { | |
return _saveImage(imageExt, prefix, &decodedImage) | |
} | |
} | |
func _saveImage(imageExt, prefix string, decodedImage *image.Image) (interface{}, error) { | |
if imageFile, err := os.Create(getRandomFileName(prefix) + "." + imageExt); err != nil { | |
return nil, err | |
} else { | |
defer imageFile.Close() | |
if imageExt == "png" { | |
if err = png.Encode(imageFile, *decodedImage); err != nil { | |
return nil, err | |
} | |
} else { | |
if err = jpeg.Encode(imageFile, *decodedImage, nil); err != nil { | |
return nil, err | |
} | |
} | |
return imageFile.Name(), nil | |
} | |
} | |
/** | |
Taken from: https://siongui.github.io/2015/04/13/go-generate-random-string/ | |
*/ | |
func getRandomFileName(prefix string) string { | |
rand.Seed(time.Now().UTC().UnixNano()) | |
l := len(prefix) | |
result := make([]byte, l) | |
for i := 0; i < l; i++ { | |
result[i] = CHARS[rand.Intn(len(CHARS))] | |
} | |
wd, _ := os.Getwd() // <-- Modified here to get an absolute file path | |
return wd + FS_PATH + prefix + string(result) | |
} |
I am glad I could help. 👍
Thank You! Will use this in one of our projects! :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very useful. I had hard times finding a working example to save base64 images. Many thanks for sharing!