前言
批量处理图片,先按短边缩放然后居中剪裁,
一、代码
package main
import (
"bufio"
"github.com/go-toast/toast"
"github.com/nfnt/resize"
"image"
_ "image/gif"
"image/jpeg"
_ "image/jpeg"
_ "image/png"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"strconv"
"strings"
)
func main() {
path, _ := os.Getwd()
fileInfos, err := ioutil.ReadDir(path)
if err != nil {
return
}
getW(path)
for _, info := range fileInfos {
if strings.HasSuffix(info.Name(), ".jpg") {
f := path + string(filepath.Separator) + info.Name()
updateImg(info.Name(), f, path)
}
}
notification := toast.Notification{
AppID: "Microsoft.Windows.Shell.RunDialog",
Title: "OK",
Message: "生成结束",
}
err = notification.Push()
if err != nil {
log.Fatalln(err)
}
}
func updateImg(name, path, p string) {
f, err := os.Open(path)
if err != nil {
panic(err)
}
m, _, err := image.Decode(f)
if err != nil {
panic(err)
}
//先缩放
//定义给定的 wi 和 wh 取自配置文件
w, err := strconv.Atoi(getW(p))
if err != nil {
return
}
h, err := strconv.Atoi(getH(p))
if err != nil {
return
}
//原图片的长和宽
wx := m.Bounds().Size().X
hy := m.Bounds().Size().Y
//以图片的短边缩放
if wx > hy {
m1 := resize.Resize(0, uint(h), m, resize.Lanczos3)
//以h为中心锚点剪裁.如果原来的图片过长则取出图片中心上下+
img := m1.(*image.YCbCr)
subImg := img.SubImage(image.Rect(img.Bounds().Size().X/2-w/2, 0, img.Bounds().Size().X/2+w/2, h)).(*image.YCbCr)
folderPath := filepath.Join(p, "NEW_IMG")
os.Mkdir(folderPath, 0777)
// 再修改权限
os.Chmod(folderPath, 0777)
folderPath1 := filepath.Join(folderPath, name)
f, _ = os.Create(folderPath1) //创建文件
defer f.Close() //关闭文件
jpeg.Encode(f, subImg, nil) //写入文件
} else {
m1 := resize.Resize(uint(w), 0, m, resize.Lanczos3)
//以h为中心锚点剪裁.如果原来的图片过长则取出图片中心上下+
img := m1.(*image.YCbCr)
subImg := img.SubImage(image.Rect(0, img.Bounds().Size().Y/2-h/2, w, img.Bounds().Size().Y/2+h/2)).(*image.YCbCr)
folderPath := filepath.Join(p, "NEW_IMG")
os.Mkdir(folderPath, 0777)
// 再修改权限
os.Chmod(folderPath, 0777)
folderPath1 := filepath.Join(folderPath, name)
f, _ = os.Create(folderPath1) //创建文件
defer f.Close() //关闭文件
jpeg.Encode(f, subImg, nil) //写入文件
}
}
// msgInfo.txt
func getW(path string) string {
path = path + "/msgInfo.txt"
fileHanle, _ := os.OpenFile(path, os.O_RDONLY, 0666)
defer fileHanle.Close()
reader := bufio.NewReader(fileHanle)
// 按行处理txt
for {
line, _, err := reader.ReadLine()
if err == io.EOF {
break
}
if strings.Contains(string(line), "W") {
return strings.Split(string(line), ":")[1]
}
}
return "100"
}
func getH(path string) string {
path = path + "/msgInfo.txt"
fileHanle, _ := os.OpenFile(path, os.O_RDONLY, 0666)
defer fileHanle.Close()
reader := bufio.NewReader(fileHanle)
// 按行处理txt
for {
line, _, err := reader.ReadLine()
if err == io.EOF {
break
}
if strings.Contains(string(line), "H") {
return strings.Split(string(line), ":")[1]
}
}
return "200"
}
二、配置文件
msgInfo.txt
三、打包
打包生成图标参考 go操作excel