From 7327c9ca448b877a96b62a1468d46482543128ec Mon Sep 17 00:00:00 2001 From: Jacob Schwartz Date: Fri, 17 Dec 2021 16:14:05 -0500 Subject: [PATCH] Allow for encoding in color --- example_test.go | 8 ++++++++ qrcode.go | 24 ++++++++++++++++++++++++ qrcode_decode_test.go | 4 ++-- 3 files changed, 34 insertions(+), 2 deletions(-) diff --git a/example_test.go b/example_test.go index 5990be0..b30f96d 100644 --- a/example_test.go +++ b/example_test.go @@ -22,6 +22,14 @@ func TestExampleEncode(t *testing.T) { } } +func TestExampleEncodeColor(t *testing.T) { + if png, err := EncodeColor("https://example.org", Medium, 256, color.RGBA{R: 255, A: 255}, color.RGBA{G: 255, A: 255}); err != nil { + t.Errorf("Error: %s", err.Error()) + } else { + fmt.Printf("PNG is %d bytes long", len(png)) + } +} + func TestExampleWriteFile(t *testing.T) { filename := "example.png" if err := WriteFile("https://example.org", Medium, 256, filename); err != nil { diff --git a/qrcode.go b/qrcode.go index d0541bc..4ea71c1 100644 --- a/qrcode.go +++ b/qrcode.go @@ -83,6 +83,30 @@ func Encode(content string, level RecoveryLevel, size int) ([]byte, error) { return q.PNG(size) } +// EncodeColor a QR Code and return a raw PNG image. +// With EncodeColor you can also specify the colors you want to use. +// +// size is both the image width and height in pixels. If size is too small then +// a larger image is silently returned. Negative values for size cause a +// variable sized image to be returned: See the documentation for Image(). +// +// To serve over HTTP, remember to send a Content-Type: image/png header. +func EncodeColor(content string, level RecoveryLevel, size int, background, + foreground color.Color) ([]byte, error) { + var q *QRCode + + q, err := New(content, level) + + q.BackgroundColor = background + q.ForegroundColor = foreground + + if err != nil { + return nil, err + } + + return q.PNG(size) +} + // WriteFile encodes, then writes a QR Code to the given filename in PNG format. // // size is both the image width and height in pixels. If size is too small then diff --git a/qrcode_decode_test.go b/qrcode_decode_test.go index 1f4b1d3..2b0756b 100644 --- a/qrcode_decode_test.go +++ b/qrcode_decode_test.go @@ -122,7 +122,7 @@ func TestDecodeAllCharacters(t *testing.T) { // zbarimg has trouble with null bytes, hence start from ASCII 1. for i := 1; i < 256; i++ { - content += string(i) + content += string(rune(i)) } q, err := New(content, Low) @@ -154,7 +154,7 @@ func TestDecodeFuzz(t *testing.T) { for j := 0; j < len; j++ { // zbarimg seems to have trouble with special characters, test printable // characters only for now. - content += string(32 + r.Intn(94)) + content += string(rune(32 + r.Intn(94))) } for _, level := range []RecoveryLevel{Low, Medium, High, Highest} {