golang: 用第三方库disintegration/imaging生成图片缩略图
一,安装第三方库:
$ go get -u github.com/disintegration/imaging
二,代码:
//得到图片的宽高
fileImg, err := os.Open(filePath) // 替换为你的图片文件路径
if err != nil {
//panic(err)
}
defer fileImg.Close()
img, _, err := image.DecodeConfig(fileImg)
if err != nil {
//panic(err)
}
fmt.Printf("Width: %d, Height: %d\n", img.Width, img.Height)
//根据大图生成缩略图
src, err := imaging.Open(filePath)
if err != nil {
//log.Fatalf("failed to open image: %v", err)
}
//生成缩略图,使长边始终为200
width:=0
height:=0
if img.Width>= img.Height {
width = 200
height = 0
} else {
height = 200
width = 0
}
//生成缩略图
dsc := imaging.Resize(src, width, height, imaging.Lanczos)
//保存缩略图
err = imaging.Save(dsc, thumbFilePath)