-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstorage.go
More file actions
89 lines (76 loc) · 2.06 KB
/
storage.go
File metadata and controls
89 lines (76 loc) · 2.06 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
package main
import (
"encoding/csv"
"log"
"os"
"path/filepath"
"sync"
"time"
)
var csvMu sync.Mutex
func appendCSV(csvPath, imagePath, reading string) error {
csvMu.Lock()
defer csvMu.Unlock()
f, err := os.OpenFile(csvPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return err
}
defer f.Close()
w := csv.NewWriter(f)
if err := w.Write([]string{imagePath, reading, time.Now().UTC().Format(time.RFC3339)}); err != nil {
return err
}
w.Flush()
return w.Error()
}
// storeImages saves the original image and, if processing was applied, the
// processed image (cropped, masked, or both) to disk.
// Returns the relative path of the original image, or empty string if storage is disabled.
func storeImages(imageData, processedData []byte, cropped, masked bool) string {
if storagePath == "" {
return ""
}
now := time.Now().UTC()
relDir := filepath.Join(
now.Format("2006"),
now.Format("01"),
now.Format("02"),
)
baseName := now.Format("15-04-05")
relPath := filepath.Join(relDir, baseName+".jpg")
fullPath := filepath.Join(storagePath, relPath)
if err := os.MkdirAll(filepath.Dir(fullPath), 0755); err != nil {
log.Printf("storage mkdir error: %v", err)
return ""
}
if err := os.WriteFile(fullPath, imageData, 0644); err != nil {
log.Printf("storage write error: %v", err)
return ""
}
if cropped || masked {
var suffix string
switch {
case cropped && masked:
suffix = "_cropped_masked"
case cropped:
suffix = "_cropped"
case masked:
suffix = "_masked"
}
procPath := filepath.Join(storagePath, relDir, baseName+suffix+".jpg")
if err := os.WriteFile(procPath, processedData, 0644); err != nil {
log.Printf("storage write %s error: %v", suffix[1:], err)
}
}
return relPath
}
// storeReading appends a row to readings.csv.
func storeReading(imagePath, reading string) {
if storagePath == "" || imagePath == "" || reading == "" {
return
}
csvPath := filepath.Join(storagePath, "readings.csv")
if err := appendCSV(csvPath, imagePath, reading); err != nil {
log.Printf("csv append error: %v", err)
}
}