Golang : Convert []byte to image
There are times when you need to convert []byte to image for saving into file purpose. I encountered one of this situation today as I need to save a generated QR code into PNG file.
In this short tutorial, we will learn how to convert []byte into image and save to a PNG file. Basically to convert to image, you just need to process the []byte variable with bytes.NewReader()
function and wrap it with image.Decode()
function.
See example :
imgByte := code.PNG()
// convert []byte to image for saving to file
img, _, _ := image.Decode(bytes.NewReader(imgByte))
//save the imgByte to file
out, err := os.Create("./QRImg.png")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
err = png.Encode(out, img)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
and the entire program :
package main
import (
"bytes"
"code.google.com/p/rsc/qr"
"crypto/rand"
"fmt"
"image"
"image/png"
"os"
"runtime"
)
func randStr(strSize int, randType string) string {
var dictionary string
if randType == "alphanum" {
dictionary = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
}
if randType == "alpha" {
dictionary = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
}
if randType == "number" {
dictionary = "0123456789"
}
var bytes = make([]byte, strSize)
rand.Read(bytes)
for k, v := range bytes {
bytes[k] = dictionary[v%byte(len(dictionary))]
}
return string(bytes)
}
func main() {
// maximize CPU usage for maximum performance
runtime.GOMAXPROCS(runtime.NumCPU())
// generate a random string - preferbly 6 or 8 characters
randomStr := randStr(6, "alphanum")
fmt.Println(randomStr)
// generate the link or any data you want to
// encode into QR codes
// in this example, we use an example of two factor
// authentication link. Replace the authTFAlink
// with yours.
authTFAlink := "otpauth://socketloop.com?key=" + randomStr + "&issuer=SocketLoop"
// Encode authTFAlink to QR codes
// qr.L = 20% redundant level
// see https://godoc.org/code.google.com/p/rsc/qr#Level
code, err := qr.Encode(authTFAlink, qr.L)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
imgByte := code.PNG()
// convert []byte to image for saving to file
img, _, _ := image.Decode(bytes.NewReader(imgByte))
//save the imgByte to file
out, err := os.Create("./QRImg.png")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
err = png.Encode(out, img)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// everything ok
fmt.Println("QR code generated and saved to QRimg.png")
}
References :
https://www.socketloop.com/tutorials/golang-save-image-to-png-jpeg-or-gif-format
https://www.socketloop.com/tutorials/golang-convert-an-image-file-to-byte
See also : Golang : Convert an image file to []byte
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
+11.2k Android Studio : Create custom icons for your application example
+5.9k Golang : Build new URL for named or registered route with Gorilla webtoolkit example
+19.9k Golang : Count number of digits from given integer value
+12.2k Golang : Search and extract certain XML data example
+4.5k Unix/Linux : How to pipe/save output of a command to file?
+6.6k How to let Facebook Login button redirect to a particular URL ?
+16.3k Golang : Merge video(OpenCV) and audio(PortAudio) into a mp4 file
+86.3k Golang : How to convert character to ASCII and back
+5.9k Java : Human readable password generator
+62.4k Golang : Convert HTTP Response body to string
+13.1k Golang : error parsing regexp: invalid or unsupported Perl syntax
+10.6k Golang : Removes punctuation or defined delimiter from the user's input