• go语言web开发系列之二十四:用imagemagick为上传图片生成缩略图


    一,安装所需的外部程序

    1,用apt-get安装ImageMagick

    root@ku:/data/liuhongdi/digv23# apt-get install imagemagick

    2,查看安装是否成功:

    1.  
      root@ku:/data/liuhongdi/digv23# convert --version
    2.  
      Version: ImageMagick 6.9.10-23 Q16 x86_64 20190101 https://imagemagick.org
    3.  
      Copyright: © 1999-2019 ImageMagick Studio LLC
    4.  
      License: https://imagemagick.org/script/license.php
    5.  
      Features: Cipher DPC Modules OpenMP
    6.  
      Delegates (built-in): bzlib djvu fftw fontconfig freetype jbig jng jp2 jpeg lcms lqr ltdl lzma openexr pangocairo png tiff webp wmf x xml zlib

    3,查看convert的默认安装路径:

    1.  
      root@ku:/data/liuhongdi/digv23# whereis convert
    2.  
      convert: /usr/bin/convert /usr/share/man/man1/convert.1.gz

    说明:刘宏缔的go森林是一个专注golang的博客,
              地址:https://blog.csdn.net/weixin_43881017

    说明:作者:刘宏缔 邮箱: 371125307@qq.com

    二,演示项目的相关信息

    1,地址:

    https://github.com/liuhongdi/digv24

    2,功能:演示go调用shell命令生成缩略图

    3,项目结构: 如图:

    三,配置文件说明

    1,config/config.yaml

    1.  
      Server:
    2.  
      RunMode: debug
    3.  
      HttpPort: 8000
    4.  
      ReadTimeout: 60
    5.  
      WriteTimeout: 60
    6.  
      Log:
    7.  
      LogFilePath: /data/gologs/logs
    8.  
      LogInfoFileName: info
    9.  
      LogWarnFileName: warn
    10.  
      LogFileExt: log
    11.  
      AccessLog:
    12.  
      LogFilePath: /data/gologs/logs
    13.  
      LogFileName: access
    14.  
      LogFileExt: log
    15.  
      Static:
    16.  
      StaticDir: /data/liuhongdi/digv24/static
    17.  
      ArticleImage:
    18.  
      UploadDir: /data/liuhongdi/digv24/static/ware/orig
    19.  
      TmbDir: /data/liuhongdi/digv24/static/ware/tmb
    20.  
      ImageHost: http://127.0.0.1:8000
    21.  
       

    说明:

    StaticDir:静态文件的保存目录

    UploadDir:文章配图的原始图上传后保存目录

    TmbDir:  文章配图的缩略图保存目录

    ImageHost:访问文章配图url的host

    四,go代码说明

    1,controller/imageController.go

    1.  
      package controller
    2.  
       
    3.  
      import (
    4.  
      "fmt"
    5.  
      "github.com/gin-gonic/gin"
    6.  
      "github.com/liuhongdi/digv24/global"
    7.  
      "github.com/liuhongdi/digv24/pkg/image"
    8.  
      "github.com/liuhongdi/digv24/pkg/result"
    9.  
      "github.com/liuhongdi/digv24/pkg/validCheck"
    10.  
      "github.com/liuhongdi/digv24/request"
    11.  
      "strconv"
    12.  
      )
    13.  
       
    14.  
      type ImageController struct{}
    15.  
       
    16.  
      func NewImageController() ImageController {
    17.  
      return ImageController{}
    18.  
      }
    19.  
      //上传单张图片
    20.  
      func (a *ImageController) UploadOne(c *gin.Context) {
    21.  
      resultRes := result.NewResult(c)
    22.  
      param := request.ArticleRequest{ID: validCheck.StrTo(c.Param("id")).MustUInt64()}
    23.  
      valid, errs := validCheck.BindAndValid(c, &param)
    24.  
      if !valid {
    25.  
      resultRes.Error(400,errs.Error())
    26.  
      return
    27.  
      }
    28.  
       
    29.  
      //save image
    30.  
      f, err := c.FormFile("f1s")
    31.  
      //错误处理
    32.  
      if err != nil {
    33.  
      fmt.Println(err.Error())
    34.  
      resultRes.Error(1,"图片上传失败")
    35.  
      } else {
    36.  
      //将文件保存至本项目根目录中
    37.  
      idstr:=strconv.FormatUint(param.ID, 10)
    38.  
      destImage := global.ArticleImageSetting.UploadDir+"/"+idstr+".jpg"
    39.  
      err := c.SaveUploadedFile(f, destImage)
    40.  
      if (err != nil){
    41.  
      fmt.Println("save err:")
    42.  
      fmt.Println(err)
    43.  
      resultRes.Error(1,"图片保存失败")
    44.  
      } else {
    45.  
      //make tmb
    46.  
      orig:= destImage
    47.  
      dest := global.ArticleImageSetting.TmbDir+"/"+idstr+".jpg"
    48.  
      err := image.ConvertByLong(orig,dest,300)
    49.  
      if (err != nil){
    50.  
      fmt.Println(err)
    51.  
      }
    52.  
      origUrl := global.ArticleImageSetting.ImageHost+"/static/ware/orig/"+idstr+".jpg"
    53.  
      tmbUrl := global.ArticleImageSetting.ImageHost+"/static/ware/tmb/"+idstr+".jpg"
    54.  
      resultRes.Success(gin.H{"origurl":origUrl,"tmburl":tmbUrl})
    55.  
      }
    56.  
      }
    57.  
      return
    58.  
      }

    2,pkg/image/convert.go

    1.  
      package image
    2.  
       
    3.  
      import (
    4.  
      "bytes"
    5.  
      "errors"
    6.  
      "fmt"
    7.  
      "os/exec"
    8.  
      "strconv"
    9.  
      )
    10.  
       
    11.  
      //按指定的图片的长边,生成缩略图
    12.  
      func ConvertByLong(orig,dest string,long int) error {
    13.  
      longstr := strconv.Itoa(long)
    14.  
      cmd := "/usr/bin/convert -size "+longstr+"x"+longstr+" -resize "+longstr+"x"+longstr+" +profile '*' "+orig+" "+dest+" 2>&1"
    15.  
      out,err := execShell(cmd)
    16.  
      fmt.Println(out)
    17.  
      fmt.Println(err)
    18.  
      if (err != nil) {
    19.  
      return err
    20.  
      }
    21.  
      if (out != "") {
    22.  
      return errors.New(out)
    23.  
      }
    24.  
      return nil
    25.  
      }
    26.  
       
    27.  
      //执行shell命令
    28.  
      func execShell(s string) (string, error){
    29.  
      //函数返回一个*Cmd,用于使用给出的参数执行name指定的程序
    30.  
      cmd := exec.Command("/bin/bash", "-c", s)
    31.  
      var out bytes.Buffer
    32.  
      cmd.Stdout = &out
    33.  
      err := cmd.Run()
    34.  
      //checkErr(err)
    35.  
      return out.String(), err
    36.  
      }

    3,static/upload.html

    1.  
      <!DOCTYPE html>
    2.  
      <html lang="zh-CN">
    3.  
      <head>
    4.  
      <title>上传文件示例</title>
    5.  
      </head>
    6.  
      <body>
    7.  
      单文件上传:<br/>
    8.  
      <form action="/image/uploadone" method="post" enctype="multipart/form-data">
    9.  
      <input type="text" name="id" id="id" placeholder="请输入id" /> <br/>
    10.  
      <input type="file" name="f1s" /><br/>
    11.  
      <input type="submit" value="上传">
    12.  
      </form>
    13.  
       
    14.  
      </body>
    15.  
      </html>

    4,其他相关代码可访问github查看

    五,测试效果

    1,打开上传页面,访问:

    http://127.0.0.1:8000/static/upload.html

    返回如图:

    上传一张图片后返回:

    点击tmburl,可以看到缩放为长边300的图片:

    六,查看库的版本

    1.  
      module github.com/liuhongdi/digv24
    2.  
       
    3.  
      go 1.15
    4.  
       
    5.  
      require (
    6.  
      github.com/gin-gonic/gin v1.6.3
    7.  
      github.com/go-playground/universal-translator v0.17.0
    8.  
      github.com/go-playground/validator/v10 v10.2.0
    9.  
      github.com/jinzhu/gorm v1.9.16
    10.  
      github.com/lestrrat/go-file-rotatelogs v0.0.0-20180223000712-d3151e2a480f
    11.  
      github.com/lestrrat/go-strftime v0.0.0-20180220042222-ba3bf9c1d042 // indirect
    12.  
      github.com/magiconair/properties v1.8.4 // indirect
    13.  
      github.com/mitchellh/mapstructure v1.3.3 // indirect
    14.  
      github.com/pelletier/go-toml v1.8.1 // indirect
    15.  
      github.com/pkg/errors v0.9.1 // indirect
    16.  
      github.com/spf13/afero v1.4.1 // indirect
    17.  
      github.com/spf13/cast v1.3.1 // indirect
    18.  
      github.com/spf13/jwalterweatherman v1.1.0 // indirect
    19.  
      github.com/spf13/pflag v1.0.5 // indirect
    20.  
      github.com/spf13/viper v1.7.1
    21.  
      go.uber.org/multierr v1.6.0 // indirect
    22.  
      go.uber.org/zap v1.16.0
    23.  
      golang.org/x/sys v0.0.0-20201119102817-f84b799fce68 // indirect
    24.  
      golang.org/x/text v0.3.4 // indirect
    25.  
      gopkg.in/ini.v1 v1.62.0 // indirect
    26.  
      gopkg.in/yaml.v2 v2.3.0 // indirect
    27.  
      )
  • 相关阅读:
    MySQL数据库----数据类型
    MySQL数据库----安装
    I2c串行总线组成及其工作原理
    感慨
    液晶操作
    串口通信
    9.19AD和DA操作
    9.19键盘的应用
    9.17键盘的操作
    9.15学习笔记
  • 原文地址:https://www.cnblogs.com/ExMan/p/14313926.html
Copyright © 2020-2023  润新知