cmd/handsum: add -b background color flag

This commit is contained in:
Nigel Tao committed 2026-04-30 21:45:26 +10:00
1 parent d534b7968a
commit f731cfc72f
4 files changed
+245 -13

No files matched your search

+49 -13
View File
@@ -18,10 +18,13 @@ import (
"errors"
"flag"
"image"
"image/draw"
"image/png"
"io"
"os"
"github.com/google/wuffs/lib/handsum"
"github.com/google/wuffs/lib/parsecolor"
_ "image/gif"
_ "image/jpeg"
@@ -36,6 +39,7 @@ var (
encodeFlag = flag.Bool("encode", false, "whether to encode the input")
roundtripFlag = flag.Bool("roundtrip", false, "whether to encode-and-decode the input")
bFlag = flag.String("b", "gray", "encoding background color: e.g. red, white, 9c27b0 or #ff8")
cFlag = flag.String("c", "rgb", "encoding color: gray or rgb [default]")
qFlag = flag.Int("q", 3, "encoding quality: 0, 1, 2 or 3 [default]")
)
@@ -57,9 +61,22 @@ Encode inputs BMP, GIF, JPEG, PNG, TIFF or WEBP and outputs Handsum.
Roundtrip is equivalent to encode (to an ephemeral file) and then decode.
For encode or roundtrip, the default color and quality is -c=rgb -q=3 (best
quality; 147 bytes per file) but you can choose a lower setting. For example:
quality; 147 bytes per file) but you can choose a lower setting. The -b flag
sets a background color (in case the input has transparency). For example:
handsum -encode -c=gray -q=2 foo.png > foo.handsum
handsum -encode -b=darkblue -c=gray -q=2 foo.png > foo.handsum
----
Flags:
-decode
-encode
-roundtrip
-b encoding background color: e.g. red, white, 9c27b0 or #ff8
-c encoding color: gray or rgb [default]
-q encoding quality: 0, 1, 2 or 3 [default]
`
func main() {
@@ -99,7 +116,7 @@ func main1() error {
return decode(inFile)
}
if !*decodeFlag && *encodeFlag && !*roundtripFlag {
return encode(inFile, color, quality)
return encode(os.Stdout, inFile, color, quality)
}
if !*decodeFlag && !*encodeFlag && *roundtripFlag {
return roundtrip(inFile, color, quality)
@@ -115,27 +132,25 @@ func decode(inFile *os.File) error {
return png.Encode(os.Stdout, src)
}
func encode(inFile *os.File, color handsum.Color, quality handsum.Quality) error {
func encode(w io.Writer, inFile *os.File, color handsum.Color, quality handsum.Quality) error {
src, _, err := image.Decode(inFile)
if err != nil {
return err
}
return handsum.Encode(os.Stdout, src, &handsum.EncodeOptions{
if o, ok := src.(interface{ Opaque() bool }); ok && !o.Opaque() {
src = applyBackgroundColor(src)
}
return handsum.Encode(w, src, &handsum.EncodeOptions{
Color: handsum.MakeOptionColor(color),
Quality: handsum.MakeOptionQuality(quality),
})
}
func roundtrip(inFile *os.File, color handsum.Color, quality handsum.Quality) error {
src, _, err := image.Decode(inFile)
if err != nil {
return err
}
buf := &bytes.Buffer{}
err = handsum.Encode(buf, src, &handsum.EncodeOptions{
Color: handsum.MakeOptionColor(color),
Quality: handsum.MakeOptionQuality(quality),
})
err := encode(buf, inFile, color, quality)
if err != nil {
return err
}
@@ -145,3 +160,24 @@ func roundtrip(inFile *os.File, color handsum.Color, quality handsum.Quality) er
}
return png.Encode(os.Stdout, dst)
}
func applyBackgroundColor(src image.Image) image.Image {
backgroundColor, _ := parsecolor.Parse(*bFlag)
r16, g16, b16, _ := backgroundColor.RGBA()
r8, g8, b8 := uint8(r16>>8), uint8(g16>>8), uint8(b16>>8)
bounds := src.Bounds()
ret := image.NewRGBA(bounds)
pix := ret.Pix
n4 := len(pix) / 4
for i4 := range n4 {
i := i4 * 4
pix[i+0] = r8
pix[i+1] = g8
pix[i+2] = b8
pix[i+3] = 0xff
}
draw.Draw(ret, bounds, src, bounds.Min, draw.Over)
return ret
}
+139
View File
@@ -0,0 +1,139 @@
// Copyright 2026 The Wuffs Authors.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//
// SPDX-License-Identifier: Apache-2.0 OR MIT
// ----------------
// Package parsecolor parses an RGB or ARGB color as hex (like "b0279c") or a
// well-known name (like "purple").
package parsecolor
import (
"image/color"
)
// Parse parses a string that's a hex color (like "#ff8" or "ffb0279c") or a
// well-known name (like "black", "purple" or "darkred"). Well-known names are
// an ad-hoc set based on the Material Design color names, optionally prefixed
// by "dark" or "light".
//
// On success, it returns ok=true. On failure, it returns ok=false and nrgba is
// the zero color.NRGBA value: transparent black.
//
// Parsing is case-insensitive.
func Parse(s string) (nrgba color.NRGBA, ok bool) {
if (len(s) <= 0) || (16 <= len(s)) {
return color.NRGBA{}, false
}
startsWithHash := s[0] == '#'
if startsWithHash {
s = s[1:]
if len(s) <= 0 {
return color.NRGBA{}, false
}
}
buf := [16]byte{}
for i := range s {
if s[i] >= 0x80 {
return color.NRGBA{}, false
}
buf[i] = s[i] | 0x20
}
if !startsWithHash {
adjustment, p, n := 0, 0, len(s)
if string(buf[:4]) == "dark" {
adjustment = 1
p += 4
n -= 4
} else if string(buf[:5]) == "light" {
adjustment = 2
p += 5
n -= 5
}
for i := 1; i < len(offsets); i++ {
o0 := int(offsets[i-0] >> 24)
o1 := int(offsets[i-1] >> 24)
if (n != o0-o1) || (string(buf[p:p+n]) != names[o1:o1+n]) {
continue
}
offset := offsets[i]
r := 0xFF & (offset >> 16)
g := 0xFF & (offset >> 8)
b := 0xFF & (offset >> 0)
if adjustment == 1 {
r /= 2
g /= 2
b /= 2
} else if adjustment == 2 {
r = 0xFF - ((0xFF - r) / 2)
g = 0xFF - ((0xFF - g) / 2)
b = 0xFF - ((0xFF - b) / 2)
}
return color.NRGBA{uint8(r), uint8(g), uint8(b), 0xFF}, true
}
}
ret, multiplier, shift := uint32(0), uint32(0), 0
if len(s) == 3 {
ret, multiplier, shift = 0xFF, 0x11, 8
} else if len(s) == 4 {
ret, multiplier, shift = 0x00, 0x11, 8
} else if len(s) == 6 {
ret, multiplier, shift = 0xFF, 0x01, 4
} else if len(s) == 8 {
ret, multiplier, shift = 0x00, 0x01, 4
} else {
return color.NRGBA{}, false
}
for i := 0; i < len(s); i++ {
c := buf[i]
if ('0' <= c) && (c <= '9') {
c -= '0'
} else if ('a' <= c) && (c <= 'f') {
c -= 'a' - 10
} else {
return color.NRGBA{}, false
}
ret <<= shift
ret |= multiplier * uint32(c)
}
return color.NRGBA{uint8(ret >> 16), uint8(ret >> 8), uint8(ret >> 0), uint8(ret >> 24)}, true
}
var offsets = [...]uint32{
0x00000000, //
0x05000000, // black
0x0AFFFFFF, // white
0x0DF44336, // red
0x11E91E63, // pink
0x179C27B0, // purple
0x1D3F51B5, // indigo
0x212196F3, // blue
0x2500BCD4, // cyan
0x29009688, // teal
0x2E4CAF50, // green
0x32CDDC39, // lime
0x38FFEB3B, // yellow
0x3DFFC107, // amber
0x43FF9800, // orange
0x48795548, // brown
0x4C9E9E9E, // gray
0x509E9E9E, // grey
}
const names = "blackwhiteredpinkpurpleindigobluecyantealgreenlimeyellowamberorangebrowngraygrey"
+55
View File
@@ -0,0 +1,55 @@
// Copyright 2026 The Wuffs Authors.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//
// SPDX-License-Identifier: Apache-2.0 OR MIT
package parsecolor
import (
"image/color"
"testing"
)
func TestParse(tt *testing.T) {
testCases := []struct {
wantColor color.NRGBA
wantOK bool
input string
}{
{color.NRGBA{0x00, 0x00, 0x00, 0xff}, true, "black"},
{color.NRGBA{0xff, 0xff, 0xff, 0xff}, true, "white"},
{color.NRGBA{0xf4, 0x43, 0x36, 0xff}, true, "red"},
{color.NRGBA{0x7a, 0x21, 0x1b, 0xff}, true, "darkred"},
{color.NRGBA{0xfa, 0xa1, 0x9b, 0xff}, true, "lightred"},
{color.NRGBA{0x26, 0x57, 0x28, 0xff}, true, "darkgreen"},
{color.NRGBA{0xff, 0x98, 0x00, 0xff}, true, "orange"},
{color.NRGBA{0xcf, 0xcf, 0xcf, 0xff}, true, "lightgray"},
{color.NRGBA{0x9e, 0x9e, 0x9e, 0xff}, true, "grey"},
{color.NRGBA{0xab, 0xc1, 0x23, 0xff}, true, "#abc123"},
{color.NRGBA{0xab, 0xc1, 0x23, 0xff}, true, "abc123"},
{color.NRGBA{0xc1, 0x23, 0x45, 0xab}, true, "abc12345"},
{color.NRGBA{0x77, 0x88, 0x99, 0xff}, true, "789"},
{color.NRGBA{0x88, 0x99, 0xaa, 0x77}, true, "789a"},
{color.NRGBA{0x00, 0x00, 0x00, 0x00}, false, "#asdf"},
{color.NRGBA{0x00, 0x00, 0x00, 0x00}, false, "darkabc123"},
{color.NRGBA{0x00, 0x00, 0x00, 0x00}, false, "dark#abc123"},
{color.NRGBA{0x00, 0x00, 0x00, 0x00}, false, "deadchannel"},
{color.NRGBA{0x00, 0x00, 0x00, 0x00}, false, "thetruthofthematter"},
}
for _, tc := range testCases {
gotColor, gotOK := Parse(tc.input)
if (gotColor != tc.wantColor) || (gotOK != tc.wantOK) {
tt.Errorf("Parse(%q): got %#v, %v, want %#v, %v",
tc.input, gotColor, gotOK, tc.wantColor, tc.wantOK)
}
}
}
+2
View File
@@ -21,6 +21,8 @@
// make these functions have static storage. This can help the compiler ignore
// or discard unused code, which can produce faster compiles and smaller
// binaries.
//
// It is a C port of the github.com/google/wuffs/lib/parsecolor library.
#ifndef PARSE_COLOR_INCLUDE_GUARD
#define PARSE_COLOR_INCLUDE_GUARD