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.
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)
}ENCODED: /9j/2wBDAAQDAwQDAwQEAwQFBAQFBgoHBgYGBg0JCgg
[truncated]
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.