¿How to decode a Base64 and convert to image and save to folder with random name?

How to decode a base64 and converted to image, and save it to a folder with random string name?

RE: first part about reading, decoding and writing:

package main

import (
	"encoding/base64"
	"io/ioutil"
)


func main() {
	// read content of the file (base64 encoded)
	encoded, err := ioutil.ReadFile("img.b64")
	if err != nil {
		// check for read error
	}

	// make slice of bytes to store the result
	decoded := make([]byte, base64.StdEncoding.EncodedLen(len(encoded)))

	// decode content of the file into slice of bytes
	_, err = base64.StdEncoding.Decode(decoded, encoded)
	if err != nil {
		// check for decode error
	}

	// write decoded bytes into new file
	err = ioutil.WriteFile("img.png", decoded, 0644)
	if err != nil {
		// check for write error
	}
}

here is the img.b64 that I used to test: https://filebin.net/px5zc5sikjqs8ywo

and regarding the random string folder - let me know if you need any help with that, otherwise this shouldn’t be too difficult to make a function for that or to find existing one.

Best wishes.

1 Like

Ill check it out tonight what if send the base64 in a post from api it will decode and save?

I read the b64 encoded string from the file, should you choose to get it from elsewhere - sure, it is your app, do what needs to be done.

base64.StdEncoding.Decode takes a slice of bytes and writes to a slice of bytes, so as long as you have slice of bytes - it doesn’t really matter where it comes from.

Regards.

1 Like

Thanks man ill check it out.

No problem at all, glad to help.

Hey dude, your works but i made a simple one is like this

package main

import (
   b64 "encoding/base64"
   "io/ioutil"
   "time"
   "math/rand"
)


func main() {
  data := "iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAQAAADa613fAAAAaUlEQVR42u3PQREAAAgDINc/9Izg34MGpJ0XIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiJyWYprx532021aAAAAAElFTkSuQmCC"
  sDec, _ := b64.StdEncoding.DecodeString(data)

  rand.Seed(time.Now().UnixNano())
  ioutil.WriteFile( randSeq(12) +".jpg",sDec, 0644)
}

var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")

func randSeq(n int) string {
    b := make([]rune, n)
    for i := range b {
        b[i] = letters[rand.Intn(len(letters))]
   }
    return string(b)
}

It converts the base64 and save it to as image with random name.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.