Golang 通過Image包實現圖片處理、二維碼生成


首先准備一個簡單的圖片 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)
}

需要導入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的二維碼圖片生成
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)
}

輸出圖片與案例二一樣。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM