-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
120 lines (99 loc) · 2.11 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
package main
/*
可选参数:
-p 要改变的图片的文件夹或者图片地址 默认根目录
-w 要改变的图片宽度 默认60
-h 要改变的图片高度 默认50
*/
import (
"flag"
"fmt"
"image/jpeg"
"io/ioutil"
"os"
"path/filepath"
"github.com/nfnt/resize"
)
var chanPN = make(chan string, 20)
func main() {
path := flag.String("p", "./", "要改变尺寸的图片所在的文件夹")
pwidth := flag.Uint("w", 60, "要改变的图片宽度")
pHight := flag.Uint("h", 50, "要改变的图片高度")
flag.Parse()
pictureName(*path, *pwidth, *pHight)
return
}
//遍历指定目录下的图片
func pictureName(path string, pWidth, pHight uint) error {
var err error
f, err := os.Stat(path)
if err != nil {
return fmtERR(err)
}
if !f.IsDir() {
path, name := filepath.Split(path)
if path == "" {
path = "./"
}
PrictureSize(path, name, pWidth, pHight)
return err
}
files, err := ioutil.ReadDir(path)
if err != nil {
return fmtERR(err)
}
for _, fi := range files {
if fi.IsDir() {
} else {
str := filepath.Ext(fi.Name())
if str != ".jpg" && str != ".JPG" {
continue
}
PrictureSize(path, fi.Name(), pWidth, pHight)
}
}
return err
}
//PrictureSize 改变传入的图片地址的图片的尺寸
func PrictureSize(savepath, pricturePath string, pWidth, pHight uint) error {
//打开图片
file, err := os.Open(pricturePath)
if err != nil {
return fmtERR(err)
}
//解码图片
img, err := jpeg.Decode(file)
if err != nil {
return fmtERR(err)
}
file.Close()
// 改变图片尺寸
m := resize.Resize(pWidth, pHight, img, resize.Lanczos3)
if err = testdir(savepath); err != nil {
return err
}
//创建新图片
out, err := os.Create(savepath + "/change/" + pricturePath)
if err != nil {
return fmtERR(err)
}
defer out.Close()
// write new image to file
jpeg.Encode(out, m, nil)
return err
}
func testdir(path string) error {
path = path + "/change"
_, err := os.Stat(path)
if err != nil {
err = os.Mkdir(path, 0666)
if err != nil {
return fmtERR(err)
}
}
return err
}
func fmtERR(err error) error {
fmt.Println(err)
return err
}