younisshah
1/6/2017 - 6:27 PM

Save a Base64 Image to disk (PNG and JPEG formats only)

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)
}