golang image图片截取、剪裁、缩略图插件imaging插件的使用
golang 图片剪裁插件imaging模块官方文档:
https://github.com/disintegration/imaging
https://pkg.go.dev/github.com/disintegration/imaging#section-readme
安装
go get -u github.com/disintegration/imaging
例子一:width和height都传了值,就按传值的比例放缩
width传了值,height传0则表示宽按传值宽度拉伸,高则等比例拉伸
func Resize(img image.Image, width, height int, filter ResampleFilter) *image.NRGBA
package itying
import (
"log"
beego "github.com/beego/beego/v2/server/web"
"github.com/disintegration/imaging"
)
type UserController struct {
beego.Controller
}
func (c *UserController) Get() {
src, err := imaging.Open("static/upload/c.png")
if err != nil {
log.Fatalf("failed to open image: %v", err)
}
//生成缩略图,尺寸150*200,并保持到为文件2.jpg
dsc := imaging.Resize(src, 150, 200, imaging.Lanczos)
err = imaging.Save(dsc, "static/upload/c_150_200.jpg")
c.Ctx.WriteString("生成图片成功")
}
最终效果 原图
生成后的图片
例子2:生成缩略图,尺寸宽100,高传0表示等比例放缩
package itying
import (
"log"
beego "github.com/beego/beego/v2/server/web"
"github.com/disintegration/imaging"
)
type UserController struct {
beego.Controller
}
func (c *UserController) Get() {
src, err := imaging.Open("static/upload/c.png")
if err != nil {
log.Fatalf("failed to open image: %v", err)
}
//生成缩略图,尺寸宽100,高传0表示等比例放缩
//最后缩略图尺寸为100*133
dsc := imaging.Resize(src, 100, 0, imaging.Lanczos)
err = imaging.Save(dsc, "static/upload/c_150_200.jpg")
c.Ctx.WriteString("用户控制器")
}
原图
剪裁后的图
例子3:生成缩略图 从中间开始截取 imaging.Center,imaging.Lanczos
package itying
import (
"log"
beego "github.com/beego/beego/v2/server/web"
"github.com/disintegration/imaging"
)
type UserController struct {
beego.Controller
}
func (c *UserController) Get() {
src, err := imaging.Open("static/upload/c.png")
if err != nil {
log.Fatalf("failed to open image: %v", err)
}
//生成缩略图,从中间截取
//imaging.Center, imaging.Lanczos
dsc := imaging.Fill(src, 120, 120, imaging.Center, imaging.Lanczos)
err = imaging.Save(dsc, "static/upload/c_100_100.jpg")
c.Ctx.WriteString("用户控制器")
}
原图
golang剪裁后的图片