base64 Encoding Example: EncodeToStringUse the encoding base64 package and calls EncodeToString. Convert a JPG image to base64.
Base64. Sometimes we want to convert images to text (by using their base64 encoding) for web pages. This can reduce requests and make things go faster.
With the encoding/base64 package, we can use the EncodeToString func in Go to get a string from a byte slice containing the image. We can then create a data URI for our image.
An example. Here we have a "coin.jpg" image in the home directory. You will want to modify the path to the location of an image that exists.
Then We use the os package (and the Open method) and the bufio package to read in all the image's bytes.
Finally We invoke base64.StdEncoding.EncodeToString to get a string from our byte slice. This is a base64 string.
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) }
Notes, program output. We truncate the output of the program, as the image is too large to be easily displayed. I verified (using an online tool) that the base64 representation is correct.
A summary. With base64, we can store images as text in an ASCII text file. This has advantages and disadvantages—too many to list here. But base64 is often useful in programming.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
© 2007-2023 Sam Allen.