-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
285 lines (252 loc) · 7.26 KB
/
main.go
File metadata and controls
285 lines (252 loc) · 7.26 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
package main
import (
"bytes"
"context"
"embed"
"encoding/base64"
"fmt"
"image"
"image/png"
"os"
"path/filepath"
"strings"
"github.com/lucasb-eyer/go-colorful"
"github.com/setanarut/layerbuilder-app/layerbuilder"
"github.com/setanarut/layerbuilder-app/layerbuilder/utils"
"github.com/wailsapp/wails/v2"
"github.com/wailsapp/wails/v2/pkg/options"
"github.com/wailsapp/wails/v2/pkg/options/assetserver"
"github.com/wailsapp/wails/v2/pkg/runtime"
)
//go:embed index.html
var assets embed.FS
func main() {
app := NewApp()
err := wails.Run(&options.App{
Title: "LayerBuilder",
Width: 900,
Height: 700,
AssetServer: &assetserver.Options{
Assets: assets,
},
BackgroundColour: &options.RGBA{R: 18, G: 18, B: 18, A: 1},
OnStartup: app.startup,
Bind: []any{
app,
},
})
if err != nil {
println("Error:", err.Error())
}
}
// App struct
type App struct {
ctx context.Context
}
type BuildOptions struct {
NumSuperpixels int
LLENeighbors int
PixelNeighbors int
Lm float64
Lr float64
Lu float64
}
// NewApp creates a new App application struct
func NewApp() *App {
return &App{}
}
// startup is called when the app starts. The context is saved
// so we can call the runtime methods
func (a *App) startup(ctx context.Context) {
a.ctx = ctx
}
// SelectOutputDir opens a native directory picker dialog and returns the selected path.
func (a *App) SelectOutputDir() string {
dir, err := runtime.OpenDirectoryDialog(a.ctx, runtime.OpenDialogOptions{
Title: "Select output folder",
})
if err != nil {
return ""
}
return dir
}
// DefaultDesktopDir returns ~/Desktop when available, otherwise the home directory.
func (a *App) DefaultDesktopDir() string {
home, err := os.UserHomeDir()
if err != nil || home == "" {
return ""
}
desktop := filepath.Join(home, "Desktop")
if st, err := os.Stat(desktop); err == nil && st.IsDir() {
return desktop
}
if st, err := os.Stat(home); err == nil && st.IsDir() {
return home
}
return ""
}
// ExtractPalette decodes a base64 PNG/JPG image and extracts N dominant colors.
// Returns a slice of hex color strings e.g. ["#a1b2c3", ...]
func (a *App) ExtractPalette(imageBase64 string, count int) ([]string, error) {
img, err := decodeBase64Image(imageBase64)
if err != nil {
return nil, fmt.Errorf("failed to decode image: %w", err)
}
palette := utils.ExtractPalette(img, count, utils.PaletteMethodDominantColor)
utils.SortPaletteByBrightness(palette)
return colorsToHex(palette), nil
}
// SortPaletteByBrightness sorts hex colors from darkest to brightest.
func (a *App) SortPaletteByBrightness(hexColors []string) ([]string, error) {
palette, err := hexToPalette(hexColors)
if err != nil {
return nil, fmt.Errorf("failed to parse palette colors: %w", err)
}
utils.SortPaletteByBrightness(palette)
return colorsToHex(palette), nil
}
// ProcessImage decodes a base64 image, builds layers with the given hex palette,
// and saves outputs to outputDir based on saveMode ("seq" or "kra").
func (a *App) ProcessImage(imageBase64 string, hexColors []string, outputDir string, opt BuildOptions, saveMode string) error {
if outputDir == "" {
return fmt.Errorf("output folder not selected")
}
img, err := decodeBase64Image(imageBase64)
if err != nil {
return fmt.Errorf("failed to decode image: %w", err)
}
palette, err := hexToPalette(hexColors)
if err != nil {
return fmt.Errorf("failed to parse palette colors: %w", err)
}
utils.SortPaletteByBrightness(palette)
builder := layerbuilder.NewLayerBuilder(img, palette)
defaultOpt := layerbuilder.OptionsFromSize(img.Bounds().Size())
finalOpt := layerbuilder.Options{
NumSuperpixels: opt.NumSuperpixels,
LLENeighbors: opt.LLENeighbors,
PixelNeighbors: opt.PixelNeighbors,
Lm: opt.Lm,
Lr: opt.Lr,
Lu: opt.Lu,
}
if finalOpt.NumSuperpixels <= 0 {
finalOpt.NumSuperpixels = defaultOpt.NumSuperpixels
}
if finalOpt.LLENeighbors <= 0 {
finalOpt.LLENeighbors = defaultOpt.LLENeighbors
}
if finalOpt.PixelNeighbors <= 0 {
finalOpt.PixelNeighbors = defaultOpt.PixelNeighbors
}
if finalOpt.Lm <= 0 {
finalOpt.Lm = defaultOpt.Lm
}
if finalOpt.Lr <= 0 {
finalOpt.Lr = defaultOpt.Lr
}
if finalOpt.Lu <= 0 {
finalOpt.Lu = defaultOpt.Lu
}
builder.Build(finalOpt)
recon := builder.Reconstruct(builder.GrayLayers())
rgbaLayers := builder.RGBALayers()
switch strings.ToLower(strings.TrimSpace(saveMode)) {
case "kra":
kraLayers := make([]image.Image, len(rgbaLayers))
for i := range rgbaLayers {
kraLayers[i] = rgbaLayers[len(rgbaLayers)-1-i]
}
kraPath := filepath.Join(outputDir, "layers.kra")
if err := utils.WriteKRA(kraPath, kraLayers); err != nil {
return fmt.Errorf("failed to write kra file: %w", err)
}
case "", "seq":
if err := utils.SaveImage(recon, filepath.Join(outputDir, "recon.png")); err != nil {
return fmt.Errorf("failed to save recon image: %w", err)
}
if err := utils.SavePalette(palette, 64, filepath.Join(outputDir, "palette.png")); err != nil {
return fmt.Errorf("failed to save palette image: %w", err)
}
if err := utils.SaveRgbaImages(rgbaLayers, outputDir+"/"); err != nil {
return fmt.Errorf("failed to save rgba sequence: %w", err)
}
default:
return fmt.Errorf("unsupported save mode: %s", saveMode)
}
return nil
}
// --- helpers ---
func decodeBase64Image(b64 string) (image.Image, error) {
// Strip data URL prefix if present (e.g. "data:image/png;base64,...")
if idx := strings.Index(b64, ","); idx != -1 {
b64 = b64[idx+1:]
}
data, err := base64.StdEncoding.DecodeString(b64)
if err != nil {
return nil, err
}
img, _, err := image.Decode(bytes.NewReader(data))
return img, err
}
func colorsToHex(palette []colorful.Color) []string {
result := make([]string, len(palette))
for i, c := range palette {
r, g, b, _ := c.RGBA()
result[i] = fmt.Sprintf("#%02x%02x%02x", r>>8, g>>8, b>>8)
}
return result
}
func hexToPalette(hexColors []string) ([]colorful.Color, error) {
palette := make([]colorful.Color, 0, len(hexColors))
for _, h := range hexColors {
h = strings.TrimPrefix(h, "#")
if len(h) != 6 {
return nil, fmt.Errorf("invalid color: #%s", h)
}
var r, g, b uint8
_, err := fmt.Sscanf(h, "%02x%02x%02x", &r, &g, &b)
if err != nil {
return nil, err
}
palette = append(palette, colorful.Color{
R: float64(r) / 255.0,
G: float64(g) / 255.0,
B: float64(b) / 255.0,
})
}
return palette, nil
}
// ThumbnailBase64 creates a small PNG thumbnail from a base64 image (max 300px wide)
// and returns it as a base64 data URL for preview.
func (a *App) ThumbnailBase64(imageBase64 string) (string, error) {
img, err := decodeBase64Image(imageBase64)
if err != nil {
return "", err
}
bounds := img.Bounds()
w := bounds.Dx()
h := bounds.Dy()
maxW := 300
var thumb image.Image
if w > maxW {
newH := h * maxW / w
dst := image.NewRGBA(image.Rect(0, 0, maxW, newH))
// simple nearest-neighbor scale
for y := 0; y < newH; y++ {
for x := 0; x < maxW; x++ {
sx := x * w / maxW
sy := y * h / newH
dst.Set(x, y, img.At(sx+bounds.Min.X, sy+bounds.Min.Y))
}
}
thumb = dst
} else {
thumb = img
}
var buf bytes.Buffer
if err := png.Encode(&buf, thumb); err != nil {
return "", err
}
return "data:image/png;base64," + base64.StdEncoding.EncodeToString(buf.Bytes()), nil
}