ZBLOG

golang 用远成图片生成一张新的图片

可以使用 Go 语言中的 image 包来生成一张新的图片。具体操作如下:

  1. 导入 image 包和远成图片包
  1. import (
  2. "image"
  3. _ "image/jpeg"
  4. "image/png"
  5. "net/http"
  6. )
  1. 下载远成图片并解码为 image.Image 类型
  1. resp, err := http.Get("https://www.example.com/image.jpg")
  2. if err != nil {
  3. // 错误处理
  4. }
  5. defer resp.Body.Close()
  6. img, _, err := image.Decode(resp.Body)
  7. if err != nil {
  8. // 错误处理
  9. }
  1. 创建一个新的 RGBA 图片
  1. newImg := image.NewRGBA(image.Rect(0, 0, width, height))

其中,width 和 height 分别为新图片的宽度和高度。

  1. 将原图复制到新图上
  1. draw.Draw(newImg, newImg.Bounds(), img, img.Bounds().Min, draw.Src)
  1. 将新图编码为 png 格式并保存到本地
  1. file, err := os.Create("newImage.png")
  2. if err != nil {
  3. // 错误处理
  4. }
  5. defer file.Close()
  6. err = png.Encode(file, newImg)
  7. if err != nil {
  8. // 错误处理
  9. }

完整代码示例:

  1. package main
  2. import (
  3. "image"
  4. _ "image/jpeg"
  5. "image/png"
  6. "net/http"
  7. "os"
  8. "log"
  9. )
  10. func main() {
  11. resp, err := http.Get("https://www.example.com/image.jpg")
  12. if err != nil {
  13. log.Fatal(err)
  14. }
  15. defer resp.Body.Close()
  16. img, _, err := image.Decode(resp.Body)
  17. if err != nil {
  18. log.Fatal(err)
  19. }
  20. width, height := 800, 600
  21. newImg := image.NewRGBA(image.Rect(0, 0, width, height))
  22. draw.Draw(newImg, newImg.Bounds(), img, img.Bounds().Min, draw.Src)
  23. file, err := os.Create("newImage.png")
  24. if err != nil {
  25. log.Fatal(err)
  26. }
  27. defer file.Close()
  28. err = png.Encode(file, newImg)
  29. if err != nil {
  30. log.Fatal(err)
  31. }
  32. }

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?