一,安装所需的外部程序
1,用apt-get安装ImageMagick
root@ku:/data/liuhongdi/digv23# apt-get install imagemagick
2,查看安装是否成功:
root@ku:/data/liuhongdi/digv23# convert --versionVersion: ImageMagick 6.9.10-23 Q16 x86_64 0101 Copyright: © 1999- ImageMagick Studio LLCLicense: /script/license.phpFeatures: Cipher DPC Modules OpenMPDelegates (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的默认安装路径:
root@ku:/data/liuhongdi/digv23# whereis convertconvert: /usr/bin/convert /usr/share/man/man1/convert.1.gz
说明:刘宏缔的go森林是一个专注golang的博客,
网站:
原文:go语言web开发系列之二十四:用imagemagick为上传图片生成缩略图 – 架构森林
说明:作者:刘宏缔 邮箱: 371125307@
二,演示项目的相关信息
1,地址:
GitHub - liuhongdi/digv24: 用imagemagick的convert命令为上传图片生成缩略图
2,功能:演示go调用shell命令生成缩略图
3,项目结构: 如图:
三,配置文件说明
1,config/config.yaml
Server:RunMode: debugHttpPort: 8000ReadTimeout: 60WriteTimeout: 60Log:LogFilePath: /data/gologs/logsLogInfoFileName: infoLogWarnFileName: warnLogFileExt: logAccessLog:LogFilePath: /data/gologs/logsLogFileName: accessLogFileExt: logStatic:StaticDir: /data/liuhongdi/digv24/staticArticleImage:UploadDir: /data/liuhongdi/digv24/static/ware/origTmbDir: /data/liuhongdi/digv24/static/ware/tmbImageHost: http://127.0.0.1:8000
说明:
StaticDir:静态文件的保存目录
UploadDir:文章配图的原始图上传后保存目录
TmbDir: 文章配图的缩略图保存目录
ImageHost:访问文章配图url的host
四,go代码说明
1,controller/imageController.go
package controllerimport ("fmt""/gin-gonic/gin""/liuhongdi/digv24/global""/liuhongdi/digv24/pkg/image""/liuhongdi/digv24/pkg/result""/liuhongdi/digv24/pkg/validCheck""/liuhongdi/digv24/request""strconv")type ImageController struct{}func NewImageController() ImageController {return ImageController{}}//上传单张图片func (a *ImageController) UploadOne(c *gin.Context) {resultRes := result.NewResult(c)param := request.ArticleRequest{ID: validCheck.StrTo(c.Param("id")).MustUInt64()}valid, errs := validCheck.BindAndValid(c, ¶m)if !valid {resultRes.Error(400,errs.Error())return}//save imagef, err := c.FormFile("f1s")//错误处理if err != nil {fmt.Println(err.Error())resultRes.Error(1,"图片上传失败")} else {//将文件保存至本项目根目录中idstr:=strconv.FormatUint(param.ID, 10)destImage := global.ArticleImageSetting.UploadDir+"/"+idstr+".jpg"err := c.SaveUploadedFile(f, destImage)if (err != nil){fmt.Println("save err:")fmt.Println(err)resultRes.Error(1,"图片保存失败")} else {//make tmborig:= destImagedest := global.ArticleImageSetting.TmbDir+"/"+idstr+".jpg"err := image.ConvertByLong(orig,dest,300)if (err != nil){fmt.Println(err)}origUrl := global.ArticleImageSetting.ImageHost+"/static/ware/orig/"+idstr+".jpg"tmbUrl := global.ArticleImageSetting.ImageHost+"/static/ware/tmb/"+idstr+".jpg"resultRes.Success(gin.H{"origurl":origUrl,"tmburl":tmbUrl})}}return}
2,pkg/image/convert.go
package imageimport ("bytes""errors""fmt""os/exec""strconv")//按指定的图片的长边,生成缩略图func ConvertByLong(orig,dest string,long int) error {longstr := strconv.Itoa(long)cmd := "/usr/bin/convert -size "+longstr+"x"+longstr+" -resize "+longstr+"x"+longstr+" +profile '*' "+orig+" "+dest+" 2>&1"out,err := execShell(cmd)fmt.Println(out)fmt.Println(err)if (err != nil) {return err}if (out != "") {return errors.New(out)}return nil}//执行shell命令func execShell(s string) (string, error){//函数返回一个*Cmd,用于使用给出的参数执行name指定的程序cmd := mand("/bin/bash", "-c", s)var out bytes.Buffercmd.Stdout = &outerr := cmd.Run()//checkErr(err)return out.String(), err}
3,static/upload.html
<!DOCTYPE html><html lang="zh-CN"><head><title>上传文件示例</title></head><body>单文件上传:<br/><form action="/image/uploadone" method="post" enctype="multipart/form-data"><input type="text" name="id" id="id" placeholder="请输入id" /> <br/><input type="file" name="f1s" /><br/><input type="submit" value="上传"></form></body></html>
4,其他相关代码可访问github查看
五,测试效果
1,打开上传页面,访问:
http://127.0.0.1:8000/static/upload.html
返回如图:
上传一张图片后返回:
点击tmburl,可以看到缩放为长边300的图片:
六,查看库的版本
module /liuhongdi/digv24go 1.15require (/gin-gonic/gin v1./go-playground/universal-translator v0./go-playground/validator/v10 v10./jinzhu/gorm v1./lestrrat/go-file-rotatelogs v0.0.0-0223000712-/lestrrat/go-strftime v0.0.0-022222-ba3bf9c1d042 // /magiconair/properties v1.8.4 // /mitchellh/mapstructure v1.3.3 // /pelletier/go-toml v1.8.1 // /pkg/errors v0.9.1 // /spf13/afero v1.4.1 // /spf13/cast v1.3.1 // /spf13/jwalterweatherman v1.1.0 // /spf13/pflag v1.0.5 // /spf13/viper v1.7./multierr v1.6.0 // /zap v1./x/sys v0.0.0-102817-f84b799fce68 // /x/text v0.3.4 // indirectgopkg.in/ini.v1 v1.62.0 // indirectgopkg.in/yaml.v2 v2.3.0 // indirect)
如果觉得《go语言web开发系列之二十四:用imagemagick为上传图片生成缩略图》对你有帮助,请点赞、收藏,并留下你的观点哦!