-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
280 lines (251 loc) · 6.15 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
package main
import (
"bytes"
"embed"
"fmt"
"image"
"io"
"math"
"os"
"strings"
"io/ioutil"
"log"
"path/filepath"
"image/color"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
_ "golang.org/x/image/webp"
g "github.com/AllenDang/giu"
"github.com/disintegration/imaging"
"github.com/harry1453/go-common-file-dialog/cfd"
"github.com/kolesa-team/go-webp/encoder"
"github.com/kolesa-team/go-webp/webp"
)
var (
threshold int32 = 20
srcDir string = ""
dstDir string = ""
allowColor bool = false
)
var logBuffer = bytes.NewBufferString("")
var ImageSuffixes = [...]string{".jpg", ".jpeg", ".png", ".webp", ".bmp", ".tiff"}
//go:embed winres/icon.png
var embedFs embed.FS
//go:embed winres/version.txt
var version string
func PickDir(title string, startDir string) (string, error) {
pickFolderDialog, err := cfd.NewSelectFolderDialog(cfd.DialogConfig{
Title: title,
Role: "ImageFolder",
})
if err != nil {
return "", err
}
if err := pickFolderDialog.Show(); err != nil {
return "", err
}
result, err := pickFolderDialog.GetResult()
return result, err
}
func DirSelector(name string, target *string) *g.RowWidget {
return g.Row(g.Button(name).OnClick(func() {
filename, err := PickDir("选择"+name, *target)
if err == nil {
*target = filename
} else {
fmt.Println("ERR:", err)
}
}), g.InputText(target))
}
func isImageExt(ext string) bool {
for _, b := range ImageSuffixes {
if b == ext {
return true
}
}
return false
}
func getBorder(img *image.NRGBA, targetColor color.Color) int {
bounds := img.Bounds()
for x := 0; x < bounds.Max.X; x++ {
for y := 0; y < bounds.Max.Y; y++ {
c := img.At(x, y)
if !isSimilarColor(c, targetColor) {
// 出现非目标颜色, 返回列坐标
// log.Printf("非目标颜色: %dx%d %v\n", x, y, c)
return x
}
}
}
return bounds.Max.X
}
// Copy the src file to dst. Any existing file will be overwritten and will not
// copy file attributes.
func CopyFile(src, dst string) error {
in, err := os.Open(src)
if err != nil {
return err
}
defer in.Close()
out, err := os.Create(dst)
if err != nil {
return err
}
defer out.Close()
_, err = io.Copy(out, in)
if err != nil {
return err
}
return out.Close()
}
func showSize(name string, img image.Image) {
bounds := img.Bounds()
log.Printf("%s大小: %dx%d\n", name, bounds.Max.X, bounds.Max.Y)
}
func saveWebp(img image.Image, path string) error {
output, err := os.Create(path)
if err != nil {
return err
}
defer output.Close()
options, err := encoder.NewLossyEncoderOptions(encoder.PresetDefault, 75)
if err != nil {
return err
}
err = webp.Encode(output, img, options)
if err != nil {
return err
}
return nil
}
// 判断两个颜色是否相似
func isSimilarColor(c1, c2 color.Color) bool {
r1, g1, b1, _ := c1.RGBA()
r2, g2, b2, _ := c2.RGBA()
dr := int64(r1) - int64(r2)
dg := int64(g1) - int64(g2)
db := int64(b1) - int64(b2)
dist := math.Sqrt(float64(dr*dr+dg*dg+db*db) / (3 * 256 * 256))
// log.Printf("Dist: %v %v => %.3f", c1, c2, dist)
return int32(dist) <= threshold
}
func handleImage(path string, dstPath string) bool {
orignalImg, err := imaging.Open(path)
if err != nil {
log.Printf("打开来源图片失败 %s\n", err)
return false
}
showSize("原始图像", orignalImg)
var targetColor color.Color
if allowColor {
targetColor = orignalImg.At(0, 0)
} else {
targetColor = color.NRGBA{0, 0, 0, 255}
}
log.Printf("目标颜色: %v\n", targetColor)
// 裁剪实现流程: 每次旋转90度并裁剪图像左侧部分, 重复4次
img := imaging.Rotate90(orignalImg)
trimmed := []int{}
same := true
for i := 0; i < 4; i++ {
delta := getBorder(img, targetColor)
trimmed = append(trimmed, delta)
// imaging.Save(img, fmt.Sprintf("%s-%d.png", dstPath, i))
if delta > 0 {
curBounds := img.Bounds()
img = imaging.Crop(img, image.Rect(delta, 0, curBounds.Max.X, curBounds.Max.Y))
same = false
}
// imaging.Save(img, fmt.Sprintf("%s-%d-crop%d.png", dstPath, i, delta))
if i < 3 {
img = imaging.Rotate90(img)
}
}
if same {
// 未进行裁剪, 执行文件复制
log.Printf("未进行裁剪, 执行文件复制\n")
CopyFile(path, dstPath)
return true
}
log.Printf("裁剪: %v\n", trimmed)
showSize("裁剪后图像", img)
ext := strings.ToLower(filepath.Ext(dstPath))
if ext == ".webp" {
err = saveWebp(img, dstPath)
} else {
err = imaging.Save(img, dstPath)
}
if err != nil {
log.Printf("保存图片失败 %s\n", err)
return false
}
return true
}
func doTransfer() {
logBuffer.Reset()
files, err := ioutil.ReadDir(srcDir)
if err != nil {
log.Printf("打开来源文件夹失败: %s", err)
return
}
total := len(files)
log.Printf("开始转换: %s -> %s\n", srcDir, dstDir)
log.Printf("共%d个文件\n", total)
updated := 0
for idx, f := range files {
name := f.Name()
ext := filepath.Ext(name)
if !isImageExt(ext) {
log.Println("跳过", name)
continue
}
log.Println("开始处理", name)
ret := handleImage(srcDir+"/"+name, dstDir+"/"+name)
if ret {
updated++
}
log.Printf("处理完毕(%d/%d) %s\n", idx+1, total, name)
}
log.Printf("处理完毕, 共转换%d/%d个\n", updated, total)
}
func loop() {
// 是否可以开始执行
canTransfer := srcDir != "" && dstDir != "" && srcDir != dstDir
// 修正阈值范围[0,200]
if threshold < 0 {
threshold = 0
} else if threshold > 200 {
threshold = 200
}
g.SingleWindow().Layout(
g.Row(
g.Label("图像去黑边工具 by AutumnSun"),
g.Button("源码").OnClick(func() {
g.OpenURL("https://github.com/AutumnSun1996/ImageTrim")
}),
),
DirSelector("输入目录", &srcDir),
DirSelector("输出目录", &dstDir),
g.Row(
g.Row(g.Label("阈值[0,200]"), g.InputInt(&threshold).Size(40)),
g.Checkbox("支持其他颜色", &allowColor),
g.Button("开始转换").Disabled(!canTransfer).OnClick(doTransfer),
),
g.Label(logBuffer.String()),
)
}
func main() {
log.SetOutput(logBuffer)
wnd := g.NewMasterWindow("图像去黑边工具"+version, 800, 600, 0)
// 设置icon
f, err := embedFs.Open("icon.png")
if err == nil {
img, err := imaging.Decode(f)
f.Close()
if err == nil {
wnd.SetIcon([]image.Image{img})
}
}
wnd.Run(loop)
}