Skip to content

Instantly share code, notes, and snippets.

@younisshah
Last active March 18, 2022 05:34
Show Gist options
  • Save younisshah/89d481b184c2d721ab99ae9b7db2857e to your computer and use it in GitHub Desktop.
Save younisshah/89d481b184c2d721ab99ae9b7db2857e to your computer and use it in GitHub Desktop.
Save a Base64 Image to disk (PNG and JPEG formats only)
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)
}
@k0fi
Copy link

k0fi commented Aug 16, 2017

Very useful. I had hard times finding a working example to save base64 images. Many thanks for sharing!

@younisshah
Copy link
Author

younisshah commented Aug 30, 2017

I am glad I could help. 👍

@MustansirZia
Copy link

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