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.
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.
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]
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.
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.