-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathimage.go
More file actions
358 lines (279 loc) · 8.3 KB
/
Copy pathimage.go
File metadata and controls
358 lines (279 loc) · 8.3 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
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
package image
import (
"encoding/json"
"errors"
"fmt"
"image"
"image/gif"
"image/jpeg"
"image/png"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/Achno/gowall/config"
"github.com/Achno/gowall/utils"
"github.com/chai2010/webp"
)
// Available formats to Encode an image in
var encoders = map[string]func(file *os.File, img image.Image) error{
"png": func(file *os.File, img image.Image) error {
png := &png.Encoder{
CompressionLevel: png.BestSpeed,
}
return png.Encode(file, img)
},
"jpg": func(file *os.File, img image.Image) error {
return jpeg.Encode(file, img, nil)
},
"jpeg": func(file *os.File, img image.Image) error {
return jpeg.Encode(file, img, nil)
},
"webp": func(file *os.File, img image.Image) error {
return webp.Encode(file, img, nil)
},
}
// Create a Processor of this interface and call 'ProcessImg'
type ImageProcessor interface {
Process(image.Image, string) (image.Image, error)
}
// NoOpImageProcessor implements ImageProcessor but does nothing.
// Its used to just to convert images from one format to another without altering them.
//
// Example from "img.webp" --> "img.png"
type NoOpImageProcessor struct{}
// Implement the Process method
func (p *NoOpImageProcessor) Process(img image.Image, options string) (image.Image, error) {
// Simply return the image without any modifications
return img, nil
}
func LoadImage(filePath string) (image.Image, error) {
file, err := os.Open(filePath)
if err != nil {
return nil, err
}
defer file.Close()
img, _, err := image.Decode(file)
return img, err
}
func SaveImage(img image.Image, filePath string, format string) error {
file, err := os.Create(filePath)
if err != nil {
return err
}
defer file.Close()
encoder, ok := encoders[strings.ToLower(format)]
if !ok {
return fmt.Errorf("unsupported format: %s", format)
}
return encoder(file, img)
}
func SaveGif(gifData gif.GIF, fileName string) error {
dirFolder, err := utils.CreateDirectory()
if err != nil {
return err
}
outFile, err := os.Create(filepath.Join(dirFolder, "gifs", fileName+".gif"))
if err != nil {
return fmt.Errorf("failed to create output file: %w", err)
}
defer outFile.Close()
err = gif.EncodeAll(outFile, &gifData)
if err != nil {
return fmt.Errorf("while Encoding gif : %w", err)
}
fmt.Printf("Gif processed and saved as %s\n\n", outFile.Name())
return nil
}
func SaveUrlAsImg(url string) (string, error) {
extension, err := utils.GetFileExtensionFromURL(url)
if err != nil {
return "", err
}
dirFolder, err := utils.CreateDirectory()
if err != nil {
return "", fmt.Errorf("while creating Directory or getting path")
}
timestamp := time.Now().Format("20060102-150405")
fileName := fmt.Sprintf("wall-%s%s", timestamp, extension)
path := filepath.Join(dirFolder, fileName)
file, err := os.Create(path)
if err != nil {
return "", fmt.Errorf("could not create file: %w", err)
}
defer file.Close()
resp, err := http.Get(url)
if err != nil {
return "", fmt.Errorf("could not fetch the URL: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("failed to fetch image: status code %d", resp.StatusCode)
}
_, err = io.Copy(file, resp.Body)
if err != nil {
return "", fmt.Errorf("could not write to file: %w", err)
}
return path, nil
}
// Opens the image on the default viewing application of every operating system.
//
// If the terminal emulator "kitty" is running --> it will print the image on the terminal
func OpenImage(filePath string) error {
if !config.GowallConfig.EnableImagePreviewing {
return nil
}
var cmd *exec.Cmd
if utils.IsKittyTerminalRunning() || utils.IsKonsoleTerminalRunning() || utils.IsGhosttyTerminalRunning() {
cmd = exec.Command("kitty", "icat", filePath)
cmd.Stdout = os.Stdout
return cmd.Run()
}
if utils.IsWeztermTerminalRunning() {
cmd = exec.Command("wezterm", "imgcat", filePath)
cmd.Stdout = os.Stdout
return cmd.Run()
}
// 300ms for gwen
switch runtime.GOOS {
case "windows":
cmd = exec.Command("rundll32", "url.dll,FileProtocolHandler", filePath)
case "darwin":
cmd = exec.Command("open", filePath)
case "linux", "freebsd", "openbsd":
cmd = exec.Command("xdg-open", filePath)
default:
return fmt.Errorf("unsupported platform")
}
return cmd.Start()
}
type ProcessOptions struct {
SaveToFile bool // Whether to save the processed image to file
OutputExt string // Optional output extension to override the original
OutputName string // Optional outputName
}
func DefaultProcessOptions() ProcessOptions {
return ProcessOptions{
SaveToFile: true,
}
}
// Processes the image depending on a processor that implements the "ImageProcessor" interface.
// You can pass an optional "ProcessOptions" struct with extra options.
func ProcessImg(imgPath string, processor ImageProcessor, theme string, opts ...ProcessOptions) (string, *image.Image, error) {
// Use default options if none provided
options := DefaultProcessOptions()
if len(opts) > 0 {
options = opts[0]
}
// Handle directory creation
dirPath, err := utils.CreateDirectory()
if err != nil {
return "", nil, fmt.Errorf("while creating directory: %w", err)
}
// Load the image
img, err := LoadImage(imgPath)
if err != nil {
return "", nil, fmt.Errorf("while loading image: %w", err)
}
// optionally specify a temporary theme via json file in runtime
if strings.HasSuffix(theme, ".json") {
expandFile := utils.ExpandHomeDirectory([]string{theme})
data, err := os.ReadFile(expandFile[0])
if err != nil {
return "", nil, fmt.Errorf("while reading the json file")
}
var tm struct {
Name string `json:"name"`
Colors []string `json:"colors"`
}
if err := json.Unmarshal(data, &tm); err != nil {
return "", nil, fmt.Errorf("while parsing json theme file")
}
if len(tm.Name) <= 0 || len(tm.Colors) < 1 {
return "", nil, fmt.Errorf("json file does not contain a name or colors")
}
clrs, err := HexToRGBASlice(tm.Colors)
if err != nil {
return "", nil, err
}
themes[strings.ToLower(tm.Name)] = Theme{
Name: tm.Name,
Colors: clrs,
}
theme = tm.Name
}
// Process the image
newImg, err := processor.Process(img, theme)
if err != nil {
return "", nil, fmt.Errorf("while processing image: %w", err)
}
// If we don't need to save, return early with the processed image
if !options.SaveToFile {
return "", &newImg, nil
}
// Handle file extension
extension := strings.ToLower(filepath.Ext(imgPath))
if extension == "" {
return "", nil, fmt.Errorf("error: Could not determine file extension")
}
extension = extension[1:] // remove '.'
// Override extension if specified
if options.OutputExt != "" {
_, exists := encoders[strings.ToLower(options.OutputExt)]
if !exists {
return "", nil, fmt.Errorf("unsupported format: %s", options.OutputExt)
}
extension = options.OutputExt
}
// Create output filename
nameOfFile := filepath.Base(imgPath)
nameOfFile = strings.TrimSuffix(nameOfFile, filepath.Ext(nameOfFile))
if options.OutputName != "" {
nameOfFile = options.OutputName
}
nameOfFile = nameOfFile + "." + extension
outputFilePath := filepath.Join(dirPath, nameOfFile)
// Save the image
err = SaveImage(newImg, outputFilePath, extension)
if err != nil {
return "", nil, fmt.Errorf("while saving image: %w in %s", err, outputFilePath)
}
fmt.Printf("Image processed and saved as %s\n\n", outputFilePath)
return outputFilePath, &newImg, nil
}
// Process images concurrently and return the first error if there was one
func ProcessBatchImgs(files []string, theme string, processor ImageProcessor) error {
var wg sync.WaitGroup
var remaining int32 = int32(len(files))
errChan := make(chan error, len(files))
for index, file := range files {
wg.Add(1)
go func(file string, index int) {
defer wg.Done()
_, _, err := ProcessImg(file, processor, theme)
if err != nil {
errChan <- fmt.Errorf("file %s : %w", file, err)
return
}
remainingCount := atomic.AddInt32(&remaining, -1)
fmt.Printf(" ::: Image %d Completed , %d Images left ::: \n", index, remainingCount)
}(file, index)
}
wg.Wait()
close(errChan)
if len(errChan) > 0 {
// return <-errChan
var errs []error
for err := range errChan {
errs = append(errs, err)
}
return errors.New(utils.FormatErrors(errs))
}
return nil
}