C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Then: We use the os package (and the Open method) and the bufio package to read in all the image's bytes.
FileFinally: We invoke base64.StdEncoding.EncodeToString to get a string from our byte slice. This is a base64 string.
StringsGolang program that uses base64 encoding, EncodeToString
package main
import (
"bufio"
"encoding/base64"
"fmt"
"io/ioutil"
"os"
)
func main() {
// Open file on disk.
f, _ := os.Open("./coin.jpg")
// Read entire JPG into byte slice.
reader := bufio.NewReader(f)
content, _ := ioutil.ReadAll(reader)
// Encode as base64.
encoded := base64.StdEncoding.EncodeToString(content)
// Print encoded data to console.
// ... The base64 image can be used as a data URI in a browser.
fmt.Println("ENCODED: " + encoded)
}
Output
ENCODED: /9j/2wBDAAQDAwQDAwQEAwQFBAQFBgoHBgYGBg0JCgg
[truncated]