package main
import (
"bytes"
"fmt"
"github.com/disintegration/imaging"
"github.com/george518/PPGo_ClipImg/coreImg"
"image"
"io/ioutil"
"log"
"os"
"strings"
"testing"
)
//判断目录是否存在
func IsDir(name string) bool {
fi, err := os.Stat(name)
if err != nil {
fmt.Println("Error: ", err)
return false
}
return fi.IsDir()
}
//创建多级目录
func CreateDir(name string) bool {
if IsDir(name) {
return true
}
if createDirImpl(name) {
return true
} else {
return false
}
}
func createDirImpl(name string) bool {
err := os.MkdirAll(name, 0777)
if err == nil {
return true
} else {
return false
}
}
func MakeDir(file string) string {
path := strings.Split(file, "/")
var newFilePath = ""
for k, p := range path {
if k != len(path)-1 {
newFilePath += p + "/"
}
}
newFilePath += "CoreImages/"
CreateDir(newFilePath)
return newFilePath + path[len(path)-1]
}
func TestImage(t *testing.T) {
path:="example/images/bags.jpg"
//打开图片
file, err := ioutil.ReadFile(path)
if err != nil {
log.Fatal(err)
}
bt := bytes.NewBuffer(file)
m, _, err := image.Decode(bt)
if err != nil {
log.Fatal(err)
}
//截取核心图片
x0, x1, y0, y1 := coreImg.CoreImg(m)
//截取图片
corePic := imaging.Crop(m, image.Rect(x0, y0, x1, y1))
//创建地址和文件名,并保存图片
newPath := MakeDir(path)
err = imaging.Save(corePic, newPath)
if err != nil {
log.Fatal(err)
}
}
原图:
裁剪后:
有疑问加站长微信联系(非本文作者)