-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
156 lines (99 loc) · 2.46 KB
/
main.go
File metadata and controls
156 lines (99 loc) · 2.46 KB
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
package main
import (
"bytes"
"flag"
"fmt"
"io"
"mime/multipart"
"net/http"
"os"
"strings"
)
const welcome = `
_
| |__ __ _ _ __ ___ _ __ ___ _____ _____ _ __
| '_ \ / _ | '__/ _ \ '_ _ \ / _ \ \ / / _ \ '__|
| |_) | (_| | | | __/ | | | | | (_) \ V / __/ |
|_.__/ \__, |_| \___|_| |_| |_|\___/ \_/ \___|_|
|___/
bgremover-cli is a tool to remove background from images
P.S: File can not be larger than 10MB
`
func checkExtension(file string) string {
elems := strings.Split(file, "/")
ext := strings.Split(elems[len(elems)-1], ".")
return ext[len(ext)-1]
}
func main() {
fmt.Println(welcome)
var file string
var outfile string
flag.StringVar(&file, "file", "", "The image file to be processed")
flag.StringVar(&outfile, "out", "", "The output file to save the processed image")
flag.Parse()
if file == "" {
fmt.Println("Please provide an image file to process")
return
}
fileExt := checkExtension(file)
if outfile == "" {
outfile = "processed_." + fileExt
}
buf := &bytes.Buffer{}
mWriter := multipart.NewWriter(buf)
f, err := os.Open(file)
fileStats, _ := f.Stat()
if fileStats.Size() > 10*1024*1024 {
fmt.Println("File is too large")
return
}
if err != nil {
fmt.Println("Error reading file")
return
}
defer f.Close()
fileWriter, err := mWriter.CreateFormFile("image", file)
if err != nil {
fmt.Println("Error creating form file")
return
}
_, err = io.Copy(fileWriter, f)
if err != nil {
fmt.Println("Error writing file")
return
}
err = mWriter.Close()
if err != nil {
fmt.Println("Error closing writer")
return
}
client := &http.Client{}
req, err := http.NewRequest("POST", "https://api-bgremover.root27.dev/api/bgremove", buf)
if err != nil {
fmt.Println("Error creating request")
return
}
req.Header.Add("Content-Type", mWriter.FormDataContentType())
response, err := client.Do(req)
if err != nil {
fmt.Println("Error processing request")
return
}
defer response.Body.Close()
outData, err := io.ReadAll(response.Body)
if err != nil {
fmt.Println("Error reading response")
return
}
err = os.WriteFile(outfile, outData, 0644)
if err != nil {
fmt.Println("Could not save processed image")
return
}
outStats, _ := os.Stat(outfile)
if outStats.Size() == 0 {
fmt.Println("Could not process image")
return
}
fmt.Println("out file: ", outfile)
}