Skip to content

Commit

Permalink
Faster palette image conversion
Browse files Browse the repository at this point in the history
  • Loading branch information
erkkah committed May 7, 2023
1 parent 498ee20 commit 5060908
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 15 deletions.
2 changes: 1 addition & 1 deletion convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ func Convert(options Options, font, target string) (int, error) {
}

if watermark {
img, err = palettize(img)
img, err = palettize(img.(*image.NRGBA))
if err != nil {
return 0, err
}
Expand Down
22 changes: 8 additions & 14 deletions image.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package tigrfont

import (
"fmt"
"image"
"image/color"
)
Expand Down Expand Up @@ -32,7 +31,7 @@ rows:
}
}

return image.Rect(img.Bounds().Min.X, minNonTransparentRow, img.Bounds().Max.X, maxNonTransparentRow)
return image.Rect(img.Bounds().Min.X, minNonTransparentRow, img.Bounds().Max.X, maxNonTransparentRow+1)
}

func whitePalette() color.Palette {
Expand All @@ -45,20 +44,15 @@ func whitePalette() color.Palette {
return p
}

func palettize(img image.Image) (image.Image, error) {
pi := image.NewPaletted(img.Bounds(), whitePalette())
func palettize(img *image.NRGBA) (image.Image, error) {
palette := whitePalette()
pi := image.NewPaletted(img.Bounds(), palette)

for x := img.Bounds().Min.X; x <= img.Bounds().Max.X; x++ {
for y := img.Bounds().Min.Y; y <= img.Bounds().Max.Y; y++ {
src := img.At(x, y)
dst := pi.Palette.Convert(src)
for x := img.Bounds().Min.X; x < img.Bounds().Max.X; x++ {
for y := img.Bounds().Min.Y; y < img.Bounds().Max.Y; y++ {
alpha := img.Pix[img.PixOffset(x, y)+3]

sr, sg, sb, sa := src.RGBA()
dr, dg, db, da := dst.RGBA()
if sr != dr || sg != dg || sb != db || sa != da {
return pi, fmt.Errorf("palette image color mismatch")
}
pi.Set(x, y, dst)
pi.Pix[pi.PixOffset(x, y)] = alpha
}
}

Expand Down

0 comments on commit 5060908

Please sign in to comment.