ZBLOG

golang 按指定尺寸将多张图片合成一张图片,也可能是多张图或加文字合成一张图

在 Golang 中,可以使用第三方库来实现将多张图片按指定尺寸合成一张图片或者将多张图或加文字合成一张图。其中比较常用的库有:

  1. “github.com/disintegration/imaging”
  2. “github.com/fogleman/gg”
  3. “github.com/nfnt/resize”

以下是一个使用”disintegration/imaging”库的例子:

  1. package main
  2. import (
  3. "image"
  4. "image/color"
  5. "log"
  6. "os"
  7. "github.com/disintegration/imaging"
  8. )
  9. func main() {
  10. // 打开两张图片
  11. file1, err := os.Open("image1.png")
  12. if err != nil {
  13. log.Fatal(err)
  14. }
  15. defer file1.Close()
  16. file2, err := os.Open("image2.png")
  17. if err != nil {
  18. log.Fatal(err)
  19. }
  20. defer file2.Close()
  21. img1, err := imaging.Decode(file1)
  22. if err != nil {
  23. log.Fatal(err)
  24. }
  25. img2, err := imaging.Decode(file2)
  26. if err != nil {
  27. log.Fatal(err)
  28. }
  29. // 按指定尺寸将两张图片合成一张
  30. dst := imaging.New(400, 300, color.NRGBA{0, 0, 0, 0})
  31. dst = imaging.Paste(dst, img1, image.Pt(0, 0))
  32. dst = imaging.Paste(dst, img2, image.Pt(200, 0))
  33. // 保存合成后的图片
  34. err = imaging.Save(dst, "result.png")
  35. if err != nil {
  36. log.Fatal(err)
  37. }
  38. }

以上代码将两张图片按指定尺寸合成了一张图片,并保存为”result.png”。可以根据需要调整代码中的参数,以实现不同的效果。

如果需要加入文字,可以使用”golang.org/x/image/font”和”github.com/golang/freetype”库来实现。以下是一个添加文字的例子:

  1. package main
  2. import (
  3. "image"
  4. "image/color"
  5. "log"
  6. "os"
  7. "github.com/disintegration/imaging"
  8. "golang.org/x/image/font"
  9. "golang.org/x/image/font/basicfont"
  10. "golang.org/x/image/math/fixed"
  11. )
  12. func main() {
  13. // 打开一张图片
  14. file, err := os.Open("image.png")
  15. if err != nil {
  16. log.Fatal(err)
  17. }
  18. defer file.Close()
  19. img, err := imaging.Decode(file)
  20. if err != nil {
  21. log.Fatal(err)
  22. }
  23. // 在图片上添加文字
  24. dst := imaging.New(400, 300, color.NRGBA{0, 0, 0, 0})
  25. dst = imaging.Paste(dst, img, image.Pt(0, 0))
  26. context := gg.NewContextForImage(dst)
  27. context.SetFont(basicfont.Face7x13)
  28. context.SetRGB(1, 1, 1)
  29. context.DrawStringAnchored("Hello, world!", 200, 150, 0.5, 0.5)
  30. // 保存合成后的图片
  31. err = context.SavePNG("result.png")
  32. if err != nil {
  33. log.Fatal(err)
  34. }
  35. }

以上代码在打开的图片上添加了一个文字,并保存为”result.png”。同样可以根据需要调整代码中的参数,以实现不同的效果。

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=2402

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?