Golang : Encode image to base64 example
We will learn how to convert an image to base64 encoded string in this tutorial. Converting image data to base64 string can be useful in situations such as - you do not want to store the image as file, image is only one-time usage or you want to embed the image directly into an HTML document. For examples, applications like QR code generation, web image capture for chat application or sensitive data that requires short live time.
Below is an example on how to convert an image file to base64 encoded string. You can modify this code to handle image created on the spot and without needing to store in file first. For instance, QR code generation. ( see https://www.socketloop.com/tutorials/golang-how-to-generate-qr-codes )
Here you go!
package main
import (
"bufio"
"encoding/base64"
"fmt"
"net/http"
"os"
)
func Home(w http.ResponseWriter, r *http.Request) {
imgFile, err := os.Open("QrImgGA.png") // a QR code image
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer imgFile.Close()
// create a new buffer base on file size
fInfo, _ := imgFile.Stat()
var size int64 = fInfo.Size()
buf := make([]byte, size)
// read file content into buffer
fReader := bufio.NewReader(imgFile)
fReader.Read(buf)
// if you create a new image instead of loading from file, encode the image to buffer instead with png.Encode()
// png.Encode(&buf, image)
// convert the buffer bytes to base64 string - use buf.Bytes() for new image
imgBase64Str := base64.StdEncoding.EncodeToString(buf)
// Embed into an html without PNG file
img2html := "<html><body><img src=\"data:image/png;base64," + imgBase64Str + "\" /></body></html>"
w.Write([]byte(fmt.Sprintf(img2html)))
}
func main() {
// http.Handler
mux := http.NewServeMux()
mux.HandleFunc("/", Home)
http.ListenAndServe(":8080", mux)
}
Sample output :
See also : Golang : How to generate QR codes?
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+10.1k Fix ERROR 1045 (28000): Access denied for user 'root'@'ip-address' (using password: YES)
+15.6k Golang : Update database with GORM example
+22.3k Generate checksum for a file in Go
+7.9k How to show different content from website server when AdBlock is detected?
+24.2k Golang : GORM read from database example
+28.2k Get file path of temporary file in Go
+5.9k Golang : Dealing with backquote
+4.1k Golang : Converting individual Jawi alphabet to Rumi(Romanized) alphabet example
+10.4k Golang : Bubble sort example
+5.8k Fix ERROR 2003 (HY000): Can't connect to MySQL server on 'IP address' (111)
+4.6k Javascript : How to get width and height of a div?
+6.8k Web : How to see your website from different countries?