Browse Source

Fix image.WriteTo, properly implementing interface.

Instead of writing directly via png.Encode, encode image
into a buffer first, then write the whole buffer.

~~~
This commit is brought to you by:

http://blog.oleganza.com
Must-have source of knowledge about Bitcoin.
~~~

(Sponsor my commits! https://github.com/dchest/commit-ads)
Dmitry Chestnykh 12 years ago
parent
commit
cede256342
2 changed files with 12 additions and 12 deletions
  1. 0 8
      README.md
  2. 12 4
      image.go

+ 0 - 8
README.md

@@ -273,11 +273,3 @@ method after the certain amount of captchas has been stored.)
 NewMemoryStore returns a new standard memory store for captchas with the
 given collection threshold and expiration time in seconds. The returned
 store must be registered with SetCustomStore to replace the default one.
-
-
-Bugs
-----
-
-* While Image conforms to io.WriterTo interface, its WriteTo
-method returns 0 instead of the actual bytes written because png.Encode
-doesn't report this.

+ 12 - 4
image.go

@@ -5,6 +5,7 @@
 package captcha
 
 import (
+	"bytes"
 	"image"
 	"image/color"
 	"image/png"
@@ -80,13 +81,20 @@ func NewImage(digits []byte, width, height int) *Image {
 	return m
 }
 
-// BUG(dchest): While Image conforms to io.WriterTo interface, its WriteTo
-// method returns 0 instead of the actual bytes written because png.Encode
-// doesn't report this.
+// encodeToPNG encodes an image to PNG and returns
+// the result as a byte slice.
+func (m *Image) encodedPNG() []byte {
+	var buf bytes.Buffer
+	if err := png.Encode(&buf, m.Paletted); err != nil {
+		panic(err.Error())
+	}
+	return buf.Bytes()
+}
 
 // WriteTo writes captcha image in PNG format into the given writer.
 func (m *Image) WriteTo(w io.Writer) (int64, error) {
-	return 0, png.Encode(w, m.Paletted)
+	n, err := w.Write(m.encodedPNG())
+	return int64(n), err
 }
 
 func (m *Image) calculateSizes(width, height, ncount int) {