| 1 | package png2svg |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "image" |
| 8 | "image/color" |
| 9 | "image/png" |
| 10 | "os" |
| 11 | "strings" |
| 12 | |
| 13 | "github.com/xyproto/tinysvg" |
| 14 | ) |
| 15 | |
| 16 | // Pixel represents a pixel at position (x,y) |
| 17 | // with color (r,g,b,a) |
| 18 | // and a bool for if this pixel has been covered by an SVG shape yet |
| 19 | type Pixel struct { |
| 20 | x int |
| 21 | y int |
| 22 | r int |
| 23 | g int |
| 24 | b int |
| 25 | a int |
| 26 | covered bool |
| 27 | } |
| 28 | |
| 29 | // Pixels is a slice of pointers to Pixel |
| 30 | type Pixels []*Pixel |
| 31 | |
| 32 | // PixelImage contains the data needed to convert a PNG to an SVG: |
| 33 | // pixels (with an overview of which pixels are covered) and |
| 34 | // an SVG document, starting with the document and root tag + |
| 35 | // colorOptimize, for if only 4096 colors should be used |
| 36 | // (short hex color strings, like #fff). |
| 37 | type PixelImage struct { |
| 38 | document *tinysvg.Document |
| 39 | svgTag *tinysvg.Tag |
| 40 | pixels Pixels |
| 41 | w int |
| 42 | h int |
| 43 | verbose bool |
| 44 | colorOptimize bool |
| 45 | } |
| 46 | |
| 47 | // SetColorOptimize can be used to set the colorOptimize flag, |
| 48 | // for using only 4096 colors. |
| 49 | func (pi *PixelImage) SetColorOptimize(enabled bool) { |
| 50 | pi.colorOptimize = enabled |
| 51 | } |
| 52 | |
| 53 | // ReadPNG tries to read the given PNG image filename and returns and image.Image |
| 54 | // and an error. If verbose is true, some basic information is printed to stdout. |
| 55 | func ReadPNG(filename string, verbose bool) (image.Image, error) { |
| 56 | if verbose { |
| 57 | fmt.Printf("Reading %s", filename) |
| 58 | defer fmt.Println() |
| 59 | } |
| 60 | f, err := os.Open(filename) |
| 61 | if err != nil { |
| 62 | return nil, err |
| 63 | } |
| 64 | defer f.Close() |
| 65 | img, err := png.Decode(f) |
| 66 | if err != nil { |
| 67 | return nil, err |
| 68 | } |
| 69 | if verbose { |
| 70 | fmt.Printf(" (%dx%d)", img.Bounds().Max.X-img.Bounds().Min.X, img.Bounds().Max.Y-img.Bounds().Min.Y) |
| 71 | } |
| 72 | return img, nil |
| 73 | } |
| 74 | |
| 75 | // Erase characters on the terminal |
| 76 | func Erase(n int) { |
| 77 | fmt.Print(strings.Repeat("\b", n)) |
| 78 | } |
| 79 | |
| 80 | // NewPixelImage initializes a new PixelImage struct, |
| 81 | // given an image.Image. |
| 82 | func NewPixelImage(img image.Image, verbose bool) *PixelImage { |
| 83 | width := img.Bounds().Max.X - img.Bounds().Min.X |
| 84 | height := img.Bounds().Max.Y - img.Bounds().Min.Y |
| 85 | |
| 86 | pixels := make(Pixels, width*height) |
| 87 | |
| 88 | var c color.NRGBA |
| 89 | if verbose { |
| 90 | fmt.Print("Interpreting image... 0%") |
| 91 | } |
| 92 | |
| 93 | percentage := 0 |
| 94 | lastPercentage := 0 |
| 95 | i := 0 |
| 96 | lastLine := img.Bounds().Max.Y |
| 97 | |
| 98 | for y := img.Bounds().Min.Y; y < img.Bounds().Max.Y; y++ { |
| 99 | |
| 100 | if verbose && y != lastLine { |
| 101 | lastPercentage = percentage |
| 102 | percentage = int((float64(y) / float64(height)) * 100.0) |
| 103 | Erase(len(fmt.Sprintf("%d%%", lastPercentage))) |
| 104 | fmt.Printf("%d%%", percentage) |
| 105 | lastLine = y |
| 106 | } |
| 107 | |
| 108 | for x := img.Bounds().Min.X; x < img.Bounds().Max.X; x++ { |
| 109 | c = color.NRGBAModel.Convert(img.At(x, y)).(color.NRGBA) |
| 110 | // Mark transparent pixels as already being "covered" (alpha == 0) |
| 111 | pixels[i] = &Pixel{x, y, int(c.R), int(c.G), int(c.B), int(c.A), c.A == 0} |
| 112 | i++ |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | // Create a new XML document with a new SVG tag |
| 117 | document, svgTag := tinysvg.NewTinySVG(width, height) |
| 118 | |
| 119 | if verbose { |
| 120 | Erase(len(fmt.Sprintf("%d%%", lastPercentage))) |
| 121 | fmt.Println("100%") |
| 122 | } |
| 123 | |
| 124 | return &PixelImage{ |
| 125 | document: document, |
| 126 | svgTag: svgTag, |
| 127 | pixels: pixels, |
| 128 | w: width, |
| 129 | h: height, |
| 130 | verbose: verbose, |
| 131 | colorOptimize: false, |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | // Done checks if all pixels are covered, in terms of being represented by an SVG element |
| 136 | // searches from the given x and y coordinate |
| 137 | func (pi *PixelImage) Done(startx, starty int) bool { |
| 138 | for y := starty; y < pi.h; y++ { |
| 139 | for x := startx; x < pi.w; x++ { |
| 140 | i := y*pi.w + x |
| 141 | if !pi.pixels[i].covered { |
| 142 | return false |
| 143 | } |
| 144 | } |
| 145 | // Start at the beginning of the line when searching the rest of the lines |
| 146 | startx = 0 |
| 147 | } |
| 148 | return true |
| 149 | } |
| 150 | |
| 151 | // At returns the RGB color at the given coordinate |
| 152 | func (pi *PixelImage) At(x, y int) (r, g, b int) { |
| 153 | i := y*pi.w + x |
| 154 | //if i >= len(pi.pixels) { |
| 155 | // panic("At out of bounds, too large coordinate") |
| 156 | //} |
| 157 | p := *pi.pixels[i] |
| 158 | return p.r, p.g, p.b |
| 159 | } |
| 160 | |
| 161 | // At2 returns the RGBA color at the given coordinate |
| 162 | func (pi *PixelImage) At2(x, y int) (r, g, b, a int) { |
| 163 | i := y*pi.w + x |
| 164 | //if i >= len(pi.pixels) { |
| 165 | // panic("At out of bounds, too large coordinate") |
| 166 | //} |
| 167 | p := *pi.pixels[i] |
| 168 | return p.r, p.g, p.b, p.a |
| 169 | } |
| 170 | |
| 171 | // Covered returns true if the pixel at the given coordinate is already covered by SVG elements |
| 172 | func (pi *PixelImage) Covered(x, y int) bool { |
| 173 | i := y*pi.w + x |
| 174 | p := *pi.pixels[i] |
| 175 | return p.covered |
| 176 | } |
| 177 | |
| 178 | // CoverAllPixels will cover all pixels that are not yet covered by an SVG element, |
| 179 | // by creating a rectangle per pixel. |
| 180 | func (pi *PixelImage) CoverAllPixels() { |
| 181 | coverCount := 0 |
| 182 | for _, p := range pi.pixels { |
| 183 | if !(*p).covered { |
| 184 | pi.svgTag.Pixel((*p).x, (*p).y, int((*p).r), int((*p).g), int((*p).b)) |
| 185 | (*p).covered = true |
| 186 | coverCount++ |
| 187 | } |
| 188 | } |
| 189 | if pi.verbose { |
| 190 | fmt.Printf("Covered %d pixels with 1x1 rectangles.\n", coverCount) |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | // CoverAllPixelsCallback will cover all pixels that are not yet covered by an SVG element, |
| 195 | // by creating a rectangle per pixel. Also takes a callback function that will be called |
| 196 | // with which pixel index the program is at and also the total pixels, for each Nth pixels (and at the start and end). |
| 197 | func (pi *PixelImage) CoverAllPixelsCallback(callbackFunc func(int, int), Nth int) { |
| 198 | coverCount := 0 |
| 199 | l := len(pi.pixels) |
| 200 | callbackFunc(0, l) |
| 201 | for i, p := range pi.pixels { |
| 202 | if !(*p).covered { |
| 203 | pi.svgTag.Pixel((*p).x, (*p).y, int((*p).r), int((*p).g), int((*p).b)) |
| 204 | (*p).covered = true |
| 205 | coverCount++ |
| 206 | } |
| 207 | if i%Nth == 0 { |
| 208 | callbackFunc(i, l) |
| 209 | } |
| 210 | } |
| 211 | callbackFunc(l-1, l) |
| 212 | if pi.verbose { |
| 213 | fmt.Printf("Covered %d pixels with 1x1 rectangles.\n", coverCount) |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | // FirstUncovered will find the first pixel that is not covered by an SVG element, |
| 218 | // starting from (startx,starty), searching row-wise, downwards. |
| 219 | func (pi *PixelImage) FirstUncovered(startx, starty int) (int, int) { |
| 220 | for y := starty; y < pi.h; y++ { |
| 221 | for x := startx; x < pi.w; x++ { |
| 222 | if !pi.pixels[y*pi.w+x].covered { |
| 223 | return x, y |
| 224 | } |
| 225 | } |
| 226 | // Start at the beginning of the line when searching the rest of the lines |
| 227 | startx = 0 |
| 228 | } |
| 229 | // This should never happen, except when debugging |
| 230 | panic("All pixels are covered") |
| 231 | } |
| 232 | |
| 233 | // colorFromLine will extract the fill color from a svg rect line. |
| 234 | // "<rect ... fill="#ff0f00" ..." gives "#ff0f00". |
| 235 | // #ff0000 is shortened to #f00. |
| 236 | // Returns false if no fill color is found. |
| 237 | // Returns an empty string if no fill color is found. |
| 238 | func colorFromLine(line []byte, lossyColorCompression bool) ([]byte, []byte, bool) { |
| 239 | if !bytes.Contains(line, []byte(" fill=\"")) { |
| 240 | return nil, nil, false |
| 241 | } |
| 242 | fields := bytes.Fields(line) |
| 243 | var ( |
| 244 | fillEquals = []byte("fill=") |
| 245 | bsq = []byte("\"") |
| 246 | elems [][]byte |
| 247 | ) |
| 248 | if lossyColorCompression { |
| 249 | for _, field := range fields { |
| 250 | if bytes.HasPrefix(field, fillEquals) { |
| 251 | // assumption: there are always quotes, so that elems[1] exists |
| 252 | elems = bytes.Split(field, bsq) |
| 253 | return elems[1], shortenColorLossy(elems[1]), true |
| 254 | } |
| 255 | } |
| 256 | } else { |
| 257 | for _, field := range fields { |
| 258 | if bytes.HasPrefix(field, fillEquals) { |
| 259 | // assumption: there are always quotes, so that elems[1] exists |
| 260 | elems = bytes.Split(field, bsq) |
| 261 | return elems[1], shortenColorLossless(elems[1]), true |
| 262 | } |
| 263 | } |
| 264 | } |
| 265 | // This should never happen |
| 266 | return nil, nil, false |
| 267 | } |
| 268 | |
| 269 | // groupLinesByFillColor will group lines that has a fill color by color, organized under <g> tags |
| 270 | // This is not the prettiest function, but it works. |
| 271 | // TODO: Rewrite, to make it prettier |
| 272 | // TODO: Benchmark |
| 273 | func groupLinesByFillColor(lines [][]byte, colorOptimize bool) [][]byte { |
| 274 | // Group lines by fill color |
| 275 | var ( |
| 276 | groupedLines = make(map[string][][]byte) |
| 277 | fillColor, shortenedFillColor []byte |
| 278 | found bool |
| 279 | ) |
| 280 | for i, line := range lines { |
| 281 | fillColor, shortenedFillColor, found = colorFromLine(line, colorOptimize) |
| 282 | if !found { |
| 283 | // skip |
| 284 | continue |
| 285 | } |
| 286 | // Erase this line. The grouped lines will be inserted at the first empty line. |
| 287 | lines[i] = make([]byte, 0) |
| 288 | // // Convert from []byte to string because map keys can't be []byte |
| 289 | cs := string(shortenedFillColor) |
| 290 | if _, ok := groupedLines[cs]; !ok { |
| 291 | // Start an empty line |
| 292 | groupedLines[cs] = make([][]byte, 0) |
| 293 | } |
| 294 | if string(fillColor) != cs { |
| 295 | line = bytes.Replace(line, fillColor, shortenedFillColor, 1) |
| 296 | } |
| 297 | line = append(line, '>') |
| 298 | groupedLines[cs] = append(groupedLines[cs], line) |
| 299 | } |
| 300 | |
| 301 | //for k, _ := range groupedLines { |
| 302 | // fmt.Println("COLOR: ", string(k)) |
| 303 | //} |
| 304 | |
| 305 | // Build a string of all lines with fillcolor, grouped by fillcolor, inside <g> tags |
| 306 | var ( |
| 307 | buf bytes.Buffer |
| 308 | from []byte |
| 309 | gfill = []byte("<g fill=\"") |
| 310 | closing = []byte("\">") |
| 311 | spacefill = []byte(" fill=\"") |
| 312 | ) |
| 313 | for key, lines := range groupedLines { |
| 314 | if len(lines) > 1 { |
| 315 | buf.Write(gfill) |
| 316 | //fmt.Printf("WRITING KEY %s\n", key) |
| 317 | buf.WriteString(key) |
| 318 | buf.Write(closing) |
| 319 | for _, line := range lines { |
| 320 | from = append(spacefill, key...) |
| 321 | buf.Write(bytes.Replace(line, append(from, '"'), []byte{}, 1)) |
| 322 | } |
| 323 | buf.Write([]byte("</g>")) |
| 324 | } else { |
| 325 | buf.Write(lines[0]) |
| 326 | } |
| 327 | } |
| 328 | // Insert the contents in the first non-empty slice of lines |
| 329 | for i, line := range lines { |
| 330 | if len(line) == 0 { |
| 331 | lines[i] = buf.Bytes() |
| 332 | break |
| 333 | } |
| 334 | } |
| 335 | // Return lines, some of them empty. One of them is a really long line with the above contents. |
| 336 | return lines |
| 337 | } |
| 338 | |
| 339 | // Bytes returns the rendered SVG document as bytes |
| 340 | func (pi *PixelImage) Bytes() []byte { |
| 341 | if pi.verbose { |
| 342 | fmt.Print("Rendering SVG...") |
| 343 | } |
| 344 | |
| 345 | // Render the SVG document |
| 346 | // TODO: pi.document.WriteTo also exists, and might be faster |
| 347 | svgDocument := pi.document.Bytes() |
| 348 | |
| 349 | if pi.verbose { |
| 350 | fmt.Println("ok") |
| 351 | fmt.Print("Grouping elements by color...") |
| 352 | } |
| 353 | |
| 354 | // TODO: Make the code related to grouping both faster and more readable |
| 355 | |
| 356 | // Group lines by fill color, insert <g> tags |
| 357 | lines := bytes.Split(svgDocument, []byte(">")) |
| 358 | lines = groupLinesByFillColor(lines, pi.colorOptimize) |
| 359 | |
| 360 | for i, line := range lines { |
| 361 | if len(line) > 0 && !bytes.HasSuffix(line, []byte(">")) { |
| 362 | lines[i] = append(line, '>') |
| 363 | } |
| 364 | } |
| 365 | // Use the line contents as the new svgDocument |
| 366 | svgDocument = bytes.Join(lines, []byte{}) |
| 367 | |
| 368 | if pi.verbose { |
| 369 | fmt.Println("ok") |
| 370 | fmt.Print("Additional optimizations...") |
| 371 | } |
| 372 | |
| 373 | // Only non-destructive and spec-conforming optimizations goes here |
| 374 | |
| 375 | // NOTE: Removing width and height for "1" gave incorrect results in GIMP. |
| 376 | // NOTE: GIMP complains about the width and height not being set, but it is set. |
| 377 | |
| 378 | // Remove all newlines |
| 379 | // Remove all spaces before closing tags |
| 380 | // Remove double spaces |
| 381 | // Remove empty x attributes |
| 382 | // Remove empty y attributes |
| 383 | // Remove empty width attributes |
| 384 | // Remove empty height attributes |
| 385 | // Remove single spaces between tags |
| 386 | |
| 387 | svgDocument = bytes.Replace(svgDocument, []byte("\n"), []byte{}, -1) |
| 388 | svgDocument = bytes.Replace(svgDocument, []byte(" />"), []byte("/>"), -1) |
| 389 | svgDocument = bytes.Replace(svgDocument, []byte(" "), []byte(" "), -1) |
| 390 | svgDocument = bytes.Replace(svgDocument, []byte(" x=\"0\""), []byte{}, -1) |
| 391 | svgDocument = bytes.Replace(svgDocument, []byte(" y=\"0\""), []byte{}, -1) |
| 392 | svgDocument = bytes.Replace(svgDocument, []byte(" width=\"0\""), []byte{}, -1) |
| 393 | svgDocument = bytes.Replace(svgDocument, []byte(" height=\"0\""), []byte{}, -1) |
| 394 | svgDocument = bytes.Replace(svgDocument, []byte("> <"), []byte("><"), -1) |
| 395 | |
| 396 | // Replacement of colors that are not shortened, colors that has been shortened |
| 397 | // and color names to even shorter strings. |
| 398 | colorReplacements := map[string][]byte{ |
| 399 | "#f0ffff": []byte("azure"), |
| 400 | "#f5f5dc": []byte("beige"), |
| 401 | "#ffe4c4": []byte("bisque"), |
| 402 | "#a52a2a": []byte("brown"), |
| 403 | "#ff7f50": []byte("coral"), |
| 404 | "#ffd700": []byte("gold"), |
| 405 | "#808080": []byte("gray"), // "grey" is also possible |
| 406 | "#008000": []byte("green"), |
| 407 | "#4b0082": []byte("indigo"), |
| 408 | "#fffff0": []byte("ivory"), |
| 409 | "#f0e68c": []byte("khaki"), |
| 410 | "#faf0e6": []byte("linen"), |
| 411 | "#800000": []byte("maroon"), |
| 412 | "#000080": []byte("navy"), |
| 413 | "#808000": []byte("olive"), |
| 414 | "#ffa500": []byte("orange"), |
| 415 | "#da70d6": []byte("orchid"), |
| 416 | "#cd853f": []byte("peru"), |
| 417 | "#ffc0cb": []byte("pink"), |
| 418 | "#dda0dd": []byte("plum"), |
| 419 | "#800080": []byte("purple"), |
| 420 | "#f00": []byte("red"), |
| 421 | "#fa8072": []byte("salmon"), |
| 422 | "#a0522d": []byte("sienna"), |
| 423 | "#c0c0c0": []byte("silver"), |
| 424 | "#fffafa": []byte("snow"), |
| 425 | "#d2b48c": []byte("tan"), |
| 426 | "#008080": []byte("teal"), |
| 427 | "#ff6347": []byte("tomato"), |
| 428 | "#ee82ee": []byte("violet"), |
| 429 | "#f5deb3": []byte("wheat"), |
| 430 | } |
| 431 | |
| 432 | // Replace colors with the shorter version |
| 433 | for k, v := range colorReplacements { |
| 434 | svgDocument = bytes.Replace(svgDocument, []byte(k), v, -1) |
| 435 | } |
| 436 | |
| 437 | if pi.verbose { |
| 438 | fmt.Println("ok") |
| 439 | } |
| 440 | |
| 441 | return svgDocument |
| 442 | } |
| 443 | |
| 444 | // WriteSVG will save the current SVG document to a file |
| 445 | func (pi *PixelImage) WriteSVG(filename string) error { |
| 446 | var ( |
| 447 | err error |
| 448 | f *os.File |
| 449 | ) |
| 450 | |
| 451 | if !pi.Done(0, 0) { |
| 452 | return errors.New("the SVG representation does not cover all pixels") |
| 453 | } |
| 454 | if filename == "-" { |
| 455 | f = os.Stdout |
| 456 | // Turn off verbose messages, so that they don't end up in the SVG output |
| 457 | pi.verbose = false |
| 458 | } else { |
| 459 | f, err = os.Create(filename) |
| 460 | if err != nil { |
| 461 | return err |
| 462 | } |
| 463 | defer f.Close() |
| 464 | } |
| 465 | |
| 466 | // Write the generated SVG image to file or to stdout |
| 467 | if _, err = f.Write(pi.Bytes()); err != nil { |
| 468 | return err |
| 469 | } |
| 470 | return nil |
| 471 | } |