Golang 通过Image包实现图片处理、二维码生成

Golang 通过Image包实现图片处理、二维码生成,第1张

首先准备一个简单的图片 qrcode.png

了解下几个处理图片的方法
image.Decode() // 得到文件的图片对象
image.NewRGBA() // 创建一个真彩色的图像对象 *RGBA
func (p *RGBA) Bounds() Rectangle { return p.Rect } // 获取图片的尺寸
func (p *RGBA) Set(x, y int, c color.Color) {} // 以像素点为单位为图像上色
func Draw(dst Image, r image.Rectangle, src image.Image, sp image.Point, op Op) {} // 图片拼接
func Encode(w io.Writer, m image.Image) error {} // 输出图片文件
案例一、将上面的图片绘制在以黑色为底的图片上:
func TestImageSplice(t *testing.T) {
	// 创建一个以黑色为底的图片
	bgImg := image.NewRGBA(image.Rect(0, 0, 300, 300))
	for x := 0; x < bgImg.Bounds().Dx(); x++ {    // 将背景图涂黑
		for y := 0; y < bgImg.Bounds().Dy(); y++ {
			bgImg.Set(x, y, color.Black)
		}
	}
	// 拿到二维码图片对象
	f, err := os.Open("./qrcode.png")
	if err != nil {
		panic(err)
	}
	qrcodeImg, _, err := image.Decode(f)
	// 将二维码图片绘制到黑色的图片上
	draw.Draw(bgImg, bgImg.Bounds(), qrcodeImg, image.Pt(0, 0), draw.Over)
	fileOut, _ := os.Create("./image.png")
	png.Encode(fileOut, bgImg)
}

案例二、自定义二维码中心的logo

需要导入resize包:

go get github.com/nfnt/resize

代码:

func TestQrcodeLogoSlice(t *testing.T) {
   qrcodeFile, err := os.Open("./qrcode.png")
   if err != nil {
      panic(err)
   }
   qrcodeImg, _, err := image.Decode(qrcodeFile)

   logoFile, err := os.Open("./logo.png")
   if err != nil {
      panic(err)
   }
   logoImg, _, err := image.Decode(logoFile)
   logoImg = resize.Resize(uint(20), uint(20), logoImg, resize.Lanczos3)

   outQrcodeImg := image.NewRGBA(qrcodeImg.Bounds())
   draw.Draw(outQrcodeImg, qrcodeImg.Bounds(), qrcodeImg, image.Pt(0,0), draw.Over)

   offset := image.Pt((outQrcodeImg.Bounds().Max.X-logoImg.Bounds().Max.X)/2, (outQrcodeImg.Bounds().Max.Y-logoImg.Bounds().Max.Y)/2)
   draw.Draw(outQrcodeImg, qrcodeImg.Bounds().Add(offset), logoImg, image.Pt(0,0), draw.Over)

   fileOut, _ := os.Create("./image.png")
   png.Encode(fileOut, outQrcodeImg)
}

案例三、使用字符串生成二维码后,将其拼接上logo
// 带logo的二维码图片生成
func TestQrcodeWithLogoGenerate(t *testing.T) {
   content := "https://baidu.com"
   code, err := qrcode.New(content, qrcode.Medium)
   if err != nil {
      return
   }
   qrcodeImg := code.Image(256)
   outImg := image.NewRGBA(qrcodeImg.Bounds())

   logoFile, err := os.Open("./logo.png")
   if err != nil {
      panic(err)
   }
   logoImg, _, err := image.Decode(logoFile)
   logoImg = resize.Resize(uint(20), uint(20), logoImg, resize.Lanczos3)

   draw.Draw(outImg, outImg.Bounds(), qrcodeImg, image.Pt(0, 0), draw.Over)
   offset := image.Pt((outImg.Bounds().Max.X-logoImg.Bounds().Max.X)/2, (outImg.Bounds().Max.Y-logoImg.Bounds().Max.Y)/2)
   draw.Draw(outImg, outImg.Bounds().Add(offset), logoImg, image.Pt(0, 0), draw.Over)

   f, err := os.Create("image.png")
   if err != nil {
      return
   }
   png.Encode(f, outImg)
}

输出图片与案例二一样。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/990101.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存