在go语言中将[]字节数组转换为图片文件示例
Go  /  管理员 发布于 1星期前   23
有些时候,你需要将[]字节转换为图像,以便保存到文件中。我今天就遇到了这种情况,我需要把生成的QR码保存到PNG文件中。
如何将[]字节转换成图像并保存为PNG文件。
基本上,要转换为图像,你只需要用bytes.NewReader()函数处理[]byte变量,并用image.Decode()函数将其包裹。
请看例子:
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)
}
完整代码:
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() {
//最大限度地提高CPU的使用率,以获得最大的性能
runtime.GOMAXPROCS(runtime.NumCPU())
//产生一个随机字符串 - 最好是6或8个字符
randomStr := randStr(6, "alphanum")
fmt.Println(randomStr)
//生成链接或任何你想要的数据
// 编码成二维码
// 在这个例子中,我们使用了一个双因素认证的例子。
// 认证链接。将authTFAlink
// 替换为你的。
authTFAlink := "otpauth://socketloop.com?key=" + randomStr + "&issuer=SocketLoop"
// 将authTFAlink编码为QR码
// qr.L = 20%的冗余级别
// 见 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()
//将[]字节转换为图像以保存在文件中
img, _, _ := image.Decode(bytes.NewReader(imgByte))
//将imgByte保存到文件中
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)
}
//ok
fmt.Println("QR code generated and saved to QRimg.png")
}
相关文章:
在go语言中将图像文件转换为[]字节数组代码示例
博主 在
2023年国务院办公厅春节放假通知:1月21日起休7天中评论 @ xiaoB 你只管努力,剩下的叫给天意;天若有情天亦老,..xiaoB 在
2023年国务院办公厅春节放假通知:1月21日起休7天中评论 会不会春节放假后又阳一次?..BUG4 在
你翻墙过吗?国内使用vpn翻墙可能会被网警抓,你需了解的事中评论 不是吧?..博主 在
go语言+beego框架中获取get,post请求的所有参数中评论 @ t1 直接在router.go文件中配就ok..Jade 在
如何在MySQL查询中获得当月记录中评论 Dear zongscan.com team, We can skyroc..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号