From 67b09086b49f1ae83cf37e9d1ec70db07ebf1f8d Mon Sep 17 00:00:00 2001 From: mappu Date: Thu, 24 Nov 2016 20:54:21 +1300 Subject: [PATCH] cmd/gopngquant: working implementation --- cmd/gopngquant/main.go | 45 ++++++++++++++++++++++++++++++------------ 1 file changed, 32 insertions(+), 13 deletions(-) diff --git a/cmd/gopngquant/main.go b/cmd/gopngquant/main.go index edb80e6..034c98a 100644 --- a/cmd/gopngquant/main.go +++ b/cmd/gopngquant/main.go @@ -4,6 +4,7 @@ import ( "flag" "fmt" "image" + "image/color" "image/png" "os" @@ -15,14 +16,36 @@ func GoImageToRgba32(im image.Image) []byte { h := im.Bounds().Max.Y ret := make([]byte, w*h*4) + p := 0 + for y := 0; y < h; y += 1 { for x := 0; x < w; x += 1 { r16, g16, b16, a16 := im.At(x, y).RGBA() // Each value ranges within [0, 0xffff] - ret[y*h+x+0] = uint8(r16 >> 8) - ret[y*h+x+1] = uint8(g16 >> 8) - ret[y*h+x+2] = uint8(b16 >> 8) - ret[y*h+x+3] = uint8(a16 >> 8) + ret[p+0] = uint8(r16 >> 8) + ret[p+1] = uint8(g16 >> 8) + ret[p+2] = uint8(b16 >> 8) + ret[p+3] = uint8(a16 >> 8) + p += 4 + } + } + + return ret +} + +func Rgb8PaletteToGoImage(w, h int, rgb8data []byte, pal color.Palette) image.Image { + rect := image.Rectangle{ + Max: image.Point{ + X: w, + Y: h, + }, + } + + ret := image.NewPaletted(rect, pal) + + for y := 0; y < h; y += 1 { + for x := 0; x < w; x += 1 { + ret.SetColorIndex(x, y, rgb8data[y*h+x]) } } @@ -42,6 +65,9 @@ func Crush(sourcefile, destfile string) error { return fmt.Errorf("png.Decode: %s", err.Error()) } + width := img.Bounds().Max.X + height := img.Bounds().Max.Y + attr, err := imagequant.NewAttributes() if err != nil { return fmt.Errorf("NewAttributes: %s", err.Error()) @@ -50,7 +76,7 @@ func Crush(sourcefile, destfile string) error { rgba32data := GoImageToRgba32(img) - iqm, err := imagequant.NewImage(attr, string(rgba32data), img.Bounds().Max.X, img.Bounds().Max.Y, 0) + iqm, err := imagequant.NewImage(attr, string(rgba32data), width, height, 0) if err != nil { return fmt.Errorf("NewImage: %s", err.Error()) } @@ -67,14 +93,7 @@ func Crush(sourcefile, destfile string) error { return fmt.Errorf("WriteRemappedImage: %s", err.Error()) } - rect := image.Rectangle{Max: image.Point{X: res.GetImageWidth(), Y: res.GetImageHeight()}} - pal := res.GetPalette() - im2 := image.NewPaletted(rect, pal) - for y := 0; y < rect.Max.Y; y += 1 { - for x := 0; x < rect.Max.X; x += 1 { - im2.Set(x, y, pal[rgb8data[y*rect.Max.Y+x]]) - } - } + im2 := Rgb8PaletteToGoImage(res.GetImageWidth(), res.GetImageHeight(), rgb8data, res.GetPalette()) fh2, err := os.OpenFile(destfile, os.O_WRONLY|os.O_CREATE, 0644) if err != nil {