diff options
author | Ondřej Surý <ondrej@sury.org> | 2011-01-17 12:40:45 +0100 |
---|---|---|
committer | Ondřej Surý <ondrej@sury.org> | 2011-01-17 12:40:45 +0100 |
commit | 3e45412327a2654a77944249962b3652e6142299 (patch) | |
tree | bc3bf69452afa055423cbe0c5cfa8ca357df6ccf /src/pkg/image | |
parent | c533680039762cacbc37db8dc7eed074c3e497be (diff) | |
download | golang-3e45412327a2654a77944249962b3652e6142299.tar.gz |
Imported Upstream version 2011.01.12upstream/2011.01.12
Diffstat (limited to 'src/pkg/image')
-rw-r--r-- | src/pkg/image/Makefile | 4 | ||||
-rw-r--r-- | src/pkg/image/color.go | 45 | ||||
-rw-r--r-- | src/pkg/image/format.go | 86 | ||||
-rw-r--r-- | src/pkg/image/geom.go | 223 | ||||
-rw-r--r-- | src/pkg/image/image.go | 482 | ||||
-rw-r--r-- | src/pkg/image/jpeg/Makefile | 4 | ||||
-rw-r--r-- | src/pkg/image/jpeg/reader.go | 33 | ||||
-rw-r--r-- | src/pkg/image/names.go | 71 | ||||
-rw-r--r-- | src/pkg/image/png/Makefile | 2 | ||||
-rw-r--r-- | src/pkg/image/png/reader.go | 248 | ||||
-rw-r--r-- | src/pkg/image/png/reader_test.go | 84 | ||||
-rw-r--r-- | src/pkg/image/png/writer.go | 162 | ||||
-rw-r--r-- | src/pkg/image/png/writer_test.go | 27 |
13 files changed, 1118 insertions, 353 deletions
diff --git a/src/pkg/image/Makefile b/src/pkg/image/Makefile index 9c886f9f9..739ad804b 100644 --- a/src/pkg/image/Makefile +++ b/src/pkg/image/Makefile @@ -2,11 +2,13 @@ # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. -include ../../Make.$(GOARCH) +include ../../Make.inc TARG=image GOFILES=\ color.go\ + format.go\ + geom.go\ image.go\ names.go\ diff --git a/src/pkg/image/color.go b/src/pkg/image/color.go index 8a865a8a0..c1345c025 100644 --- a/src/pkg/image/color.go +++ b/src/pkg/image/color.go @@ -103,6 +103,27 @@ func (c Alpha16Color) RGBA() (r, g, b, a uint32) { return a, a, a, a } +// A GrayColor represents an 8-bit grayscale color. +type GrayColor struct { + Y uint8 +} + +func (c GrayColor) RGBA() (r, g, b, a uint32) { + y := uint32(c.Y) + y |= y << 8 + return y, y, y, 0xffff +} + +// A Gray16Color represents a 16-bit grayscale color. +type Gray16Color struct { + Y uint16 +} + +func (c Gray16Color) RGBA() (r, g, b, a uint32) { + y := uint32(c.Y) + return y, y, y, 0xffff +} + // A ColorModel can convert foreign Colors, with a possible loss of precision, // to a Color from its own color model. type ColorModel interface { @@ -187,6 +208,24 @@ func toAlpha16Color(c Color) Color { return Alpha16Color{uint16(a)} } +func toGrayColor(c Color) Color { + if _, ok := c.(GrayColor); ok { + return c + } + r, g, b, _ := c.RGBA() + y := (299*r + 587*g + 114*b + 500) / 1000 + return GrayColor{uint8(y >> 8)} +} + +func toGray16Color(c Color) Color { + if _, ok := c.(Gray16Color); ok { + return c + } + r, g, b, _ := c.RGBA() + y := (299*r + 587*g + 114*b + 500) / 1000 + return Gray16Color{uint16(y)} +} + // The ColorModel associated with RGBAColor. var RGBAColorModel ColorModel = ColorModelFunc(toRGBAColor) @@ -204,3 +243,9 @@ var AlphaColorModel ColorModel = ColorModelFunc(toAlphaColor) // The ColorModel associated with Alpha16Color. var Alpha16ColorModel ColorModel = ColorModelFunc(toAlpha16Color) + +// The ColorModel associated with GrayColor. +var GrayColorModel ColorModel = ColorModelFunc(toGrayColor) + +// The ColorModel associated with Gray16Color. +var Gray16ColorModel ColorModel = ColorModelFunc(toGray16Color) diff --git a/src/pkg/image/format.go b/src/pkg/image/format.go new file mode 100644 index 000000000..1d541b094 --- /dev/null +++ b/src/pkg/image/format.go @@ -0,0 +1,86 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package image + +import ( + "bufio" + "io" + "os" +) + +// An UnknownFormatErr indicates that decoding encountered an unknown format. +var UnknownFormatErr = os.NewError("image: unknown format") + +// A format holds an image format's name, magic header and how to decode it. +type format struct { + name, magic string + decode func(io.Reader) (Image, os.Error) + decodeConfig func(io.Reader) (Config, os.Error) +} + +// Formats is the list of registered formats. +var formats []format + +// RegisterFormat registers an image format for use by Decode. +// Name is the name of the format, like "jpeg" or "png". +// Magic is the magic prefix that identifies the format's encoding. +// Decode is the function that decodes the encoded image. +// DecodeConfig is the function that decodes just its configuration. +func RegisterFormat(name, magic string, decode func(io.Reader) (Image, os.Error), decodeConfig func(io.Reader) (Config, os.Error)) { + formats = append(formats, format{name, magic, decode, decodeConfig}) +} + +// A reader is an io.Reader that can also peek ahead. +type reader interface { + io.Reader + Peek(int) ([]byte, os.Error) +} + +// AsReader converts an io.Reader to a reader. +func asReader(r io.Reader) reader { + if rr, ok := r.(reader); ok { + return rr + } + return bufio.NewReader(r) +} + +// sniff determines the format of r's data. +func sniff(r reader) format { + for _, f := range formats { + s, err := r.Peek(len(f.magic)) + if err == nil && string(s) == f.magic { + return f + } + } + return format{} +} + +// Decode decodes an image that has been encoded in a registered format. +// The string returned is the format name used during format registration. +// Format registration is typically done by the init method of the codec- +// specific package. +func Decode(r io.Reader) (Image, string, os.Error) { + rr := asReader(r) + f := sniff(rr) + if f.decode == nil { + return nil, "", UnknownFormatErr + } + m, err := f.decode(rr) + return m, f.name, err +} + +// DecodeConfig decodes the color model and dimensions of an image that has +// been encoded in a registered format. The string returned is the format name +// used during format registration. Format registration is typically done by +// the init method of the codec-specific package. +func DecodeConfig(r io.Reader) (Config, string, os.Error) { + rr := asReader(r) + f := sniff(rr) + if f.decodeConfig == nil { + return Config{}, "", UnknownFormatErr + } + c, err := f.decodeConfig(rr) + return c, f.name, err +} diff --git a/src/pkg/image/geom.go b/src/pkg/image/geom.go new file mode 100644 index 000000000..ccfe9cdb0 --- /dev/null +++ b/src/pkg/image/geom.go @@ -0,0 +1,223 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package image + +import ( + "strconv" +) + +// A Point is an X, Y coordinate pair. The axes increase right and down. +type Point struct { + X, Y int +} + +// String returns a string representation of p like "(3,4)". +func (p Point) String() string { + return "(" + strconv.Itoa(p.X) + "," + strconv.Itoa(p.Y) + ")" +} + +// Add returns the vector p+q. +func (p Point) Add(q Point) Point { + return Point{p.X + q.X, p.Y + q.Y} +} + +// Sub returns the vector p-q. +func (p Point) Sub(q Point) Point { + return Point{p.X - q.X, p.Y - q.Y} +} + +// Mul returns the vector p*k. +func (p Point) Mul(k int) Point { + return Point{p.X * k, p.Y * k} +} + +// Div returns the vector p/k. +func (p Point) Div(k int) Point { + return Point{p.X / k, p.Y / k} +} + +// Mod returns the point q in r such that p.X-q.X is a multiple of r's width +// and p.Y-q.Y is a multiple of r's height. +func (p Point) Mod(r Rectangle) Point { + w, h := r.Dx(), r.Dy() + p = p.Sub(r.Min) + p.X = p.X % w + if p.X < 0 { + p.X += w + } + p.Y = p.Y % h + if p.Y < 0 { + p.Y += h + } + return p.Add(r.Min) +} + +// Eq returns whether p and q are equal. +func (p Point) Eq(q Point) bool { + return p.X == q.X && p.Y == q.Y +} + +// ZP is the zero Point. +var ZP Point + +// Pt is shorthand for Point{X, Y}. +func Pt(X, Y int) Point { + return Point{X, Y} +} + +// A Rectangle contains the points with Min.X <= X < Max.X, Min.Y <= Y < Max.Y. +// It is well-formed if Min.X <= Max.X and likewise for Y. Points are always +// well-formed. A rectangle's methods always return well-formed outputs for +// well-formed inputs. +type Rectangle struct { + Min, Max Point +} + +// String returns a string representation of r like "(3,4)-(6,5)". +func (r Rectangle) String() string { + return r.Min.String() + "-" + r.Max.String() +} + +// Dx returns r's width. +func (r Rectangle) Dx() int { + return r.Max.X - r.Min.X +} + +// Dy returns r's height. +func (r Rectangle) Dy() int { + return r.Max.Y - r.Min.Y +} + +// Size returns r's width and height. +func (r Rectangle) Size() Point { + return Point{ + r.Max.X - r.Min.X, + r.Max.Y - r.Min.Y, + } +} + +// Add returns the rectangle r translated by p. +func (r Rectangle) Add(p Point) Rectangle { + return Rectangle{ + Point{r.Min.X + p.X, r.Min.Y + p.Y}, + Point{r.Max.X + p.X, r.Max.Y + p.Y}, + } +} + +// Add returns the rectangle r translated by -p. +func (r Rectangle) Sub(p Point) Rectangle { + return Rectangle{ + Point{r.Min.X - p.X, r.Min.Y - p.Y}, + Point{r.Max.X - p.X, r.Max.Y - p.Y}, + } +} + +// Inset returns the rectangle r inset by n, which may be negative. If either +// of r's dimensions is less than 2*n then an empty rectangle near the center +// of r will be returned. +func (r Rectangle) Inset(n int) Rectangle { + if r.Dx() < 2*n { + r.Min.X = (r.Min.X + r.Max.X) / 2 + r.Max.X = r.Min.X + } else { + r.Min.X += n + r.Max.X -= n + } + if r.Dy() < 2*n { + r.Min.Y = (r.Min.Y + r.Max.Y) / 2 + r.Max.Y = r.Min.Y + } else { + r.Min.Y += n + r.Max.Y -= n + } + return r +} + +// Intersect returns the largest rectangle contained by both r and s. If the +// two rectangles do not overlap then the zero rectangle will be returned. +func (r Rectangle) Intersect(s Rectangle) Rectangle { + if r.Min.X < s.Min.X { + r.Min.X = s.Min.X + } + if r.Min.Y < s.Min.Y { + r.Min.Y = s.Min.Y + } + if r.Max.X > s.Max.X { + r.Max.X = s.Max.X + } + if r.Max.Y > s.Max.Y { + r.Max.Y = s.Max.Y + } + if r.Min.X > r.Max.X || r.Min.Y > r.Max.Y { + return ZR + } + return r +} + +// Union returns the smallest rectangle that contains both r and s. +func (r Rectangle) Union(s Rectangle) Rectangle { + if r.Min.X > s.Min.X { + r.Min.X = s.Min.X + } + if r.Min.Y > s.Min.Y { + r.Min.Y = s.Min.Y + } + if r.Max.X < s.Max.X { + r.Max.X = s.Max.X + } + if r.Max.Y < s.Max.Y { + r.Max.Y = s.Max.Y + } + return r +} + +// Empty returns whether the rectangle contains no points. +func (r Rectangle) Empty() bool { + return r.Min.X >= r.Max.X || r.Min.Y >= r.Max.Y +} + +// Eq returns whether r and s are equal. +func (r Rectangle) Eq(s Rectangle) bool { + return r.Min.X == s.Min.X && r.Min.Y == s.Min.Y && + r.Max.X == s.Max.X && r.Max.Y == s.Max.Y +} + +// Overlaps returns whether r and s have a non-empty intersection. +func (r Rectangle) Overlaps(s Rectangle) bool { + return r.Min.X < s.Max.X && s.Min.X < r.Max.X && + r.Min.Y < s.Max.Y && s.Min.Y < r.Max.Y +} + +// Contains returns whether r contains p. +func (r Rectangle) Contains(p Point) bool { + return p.X >= r.Min.X && p.X < r.Max.X && + p.Y >= r.Min.Y && p.Y < r.Max.Y +} + +// Canon returns the canonical version of r. The returned rectangle has minimum +// and maximum coordinates swapped if necessary so that it is well-formed. +func (r Rectangle) Canon() Rectangle { + if r.Max.X < r.Min.X { + r.Min.X, r.Max.X = r.Max.X, r.Min.X + } + if r.Max.Y < r.Min.Y { + r.Min.Y, r.Max.Y = r.Max.Y, r.Min.Y + } + return r +} + +// ZR is the zero Rectangle. +var ZR Rectangle + +// Rect is shorthand for Rectangle{Pt(x0, y0), Pt(x1, y1)}. +func Rect(x0, y0, x1, y1 int) Rectangle { + if x0 > x1 { + x0, x1 = x1, x0 + } + if y0 > y1 { + y0, y1 = y1, y0 + } + return Rectangle{Point{x0, y0}, Point{x1, y1}} +} diff --git a/src/pkg/image/image.go b/src/pkg/image/image.go index decf1ce43..c0e96e1f7 100644 --- a/src/pkg/image/image.go +++ b/src/pkg/image/image.go @@ -5,50 +5,67 @@ // The image package implements a basic 2-D image library. package image -// An Image is a rectangular grid of Colors drawn from a ColorModel. +// A Config consists of an image's color model and dimensions. +type Config struct { + ColorModel ColorModel + Width, Height int +} + +// An Image is a finite rectangular grid of Colors drawn from a ColorModel. type Image interface { + // ColorModel returns the Image's ColorModel. ColorModel() ColorModel - Width() int - Height() int - // At(0, 0) returns the upper-left pixel of the grid. - // At(Width()-1, Height()-1) returns the lower-right pixel. + // Bounds returns the domain for which At can return non-zero color. + // The bounds do not necessarily contain the point (0, 0). + Bounds() Rectangle + // At returns the color of the pixel at (x, y). + // At(Bounds().Min.X, Bounds().Min.Y) returns the upper-left pixel of the grid. + // At(Bounds().Max.X-1, Bounds().Max.Y-1) returns the lower-right one. At(x, y int) Color } -// An RGBA is an in-memory image backed by a 2-D slice of RGBAColor values. +// An RGBA is an in-memory image of RGBAColor values. type RGBA struct { - // The Pixel field's indices are y first, then x, so that At(x, y) == Pixel[y][x]. - Pixel [][]RGBAColor + // Pix holds the image's pixels. The pixel at (x, y) is Pix[y*Stride+x]. + Pix []RGBAColor + Stride int + // Rect is the image's bounds. + Rect Rectangle } func (p *RGBA) ColorModel() ColorModel { return RGBAColorModel } -func (p *RGBA) Width() int { - if len(p.Pixel) == 0 { - return 0 +func (p *RGBA) Bounds() Rectangle { return p.Rect } + +func (p *RGBA) At(x, y int) Color { + if !p.Rect.Contains(Point{x, y}) { + return RGBAColor{} } - return len(p.Pixel[0]) + return p.Pix[y*p.Stride+x] } -func (p *RGBA) Height() int { return len(p.Pixel) } - -func (p *RGBA) At(x, y int) Color { return p.Pixel[y][x] } - -func (p *RGBA) Set(x, y int, c Color) { p.Pixel[y][x] = toRGBAColor(c).(RGBAColor) } +func (p *RGBA) Set(x, y int, c Color) { + if !p.Rect.Contains(Point{x, y}) { + return + } + p.Pix[y*p.Stride+x] = toRGBAColor(c).(RGBAColor) +} // Opaque scans the entire image and returns whether or not it is fully opaque. func (p *RGBA) Opaque() bool { - h := len(p.Pixel) - if h > 0 { - w := len(p.Pixel[0]) - for y := 0; y < h; y++ { - pix := p.Pixel[y] - for x := 0; x < w; x++ { - if pix[x].A != 0xff { - return false - } + if p.Rect.Empty() { + return true + } + base := p.Rect.Min.Y * p.Stride + i0, i1 := base+p.Rect.Min.X, base+p.Rect.Max.X + for y := p.Rect.Min.Y; y < p.Rect.Max.Y; y++ { + for _, c := range p.Pix[i0:i1] { + if c.A != 0xff { + return false } } + i0 += p.Stride + i1 += p.Stride } return true } @@ -56,251 +73,343 @@ func (p *RGBA) Opaque() bool { // NewRGBA returns a new RGBA with the given width and height. func NewRGBA(w, h int) *RGBA { buf := make([]RGBAColor, w*h) - pix := make([][]RGBAColor, h) - for y := range pix { - pix[y] = buf[w*y : w*(y+1)] - } - return &RGBA{pix} + return &RGBA{buf, w, Rectangle{ZP, Point{w, h}}} } -// An RGBA64 is an in-memory image backed by a 2-D slice of RGBA64Color values. +// An RGBA64 is an in-memory image of RGBA64Color values. type RGBA64 struct { - // The Pixel field's indices are y first, then x, so that At(x, y) == Pixel[y][x]. - Pixel [][]RGBA64Color + // Pix holds the image's pixels. The pixel at (x, y) is Pix[y*Stride+x]. + Pix []RGBA64Color + Stride int + // Rect is the image's bounds. + Rect Rectangle } func (p *RGBA64) ColorModel() ColorModel { return RGBA64ColorModel } -func (p *RGBA64) Width() int { - if len(p.Pixel) == 0 { - return 0 +func (p *RGBA64) Bounds() Rectangle { return p.Rect } + +func (p *RGBA64) At(x, y int) Color { + if !p.Rect.Contains(Point{x, y}) { + return RGBA64Color{} } - return len(p.Pixel[0]) + return p.Pix[y*p.Stride+x] } -func (p *RGBA64) Height() int { return len(p.Pixel) } - -func (p *RGBA64) At(x, y int) Color { return p.Pixel[y][x] } - -func (p *RGBA64) Set(x, y int, c Color) { p.Pixel[y][x] = toRGBA64Color(c).(RGBA64Color) } +func (p *RGBA64) Set(x, y int, c Color) { + if !p.Rect.Contains(Point{x, y}) { + return + } + p.Pix[y*p.Stride+x] = toRGBA64Color(c).(RGBA64Color) +} // Opaque scans the entire image and returns whether or not it is fully opaque. func (p *RGBA64) Opaque() bool { - h := len(p.Pixel) - if h > 0 { - w := len(p.Pixel[0]) - for y := 0; y < h; y++ { - pix := p.Pixel[y] - for x := 0; x < w; x++ { - if pix[x].A != 0xffff { - return false - } + if p.Rect.Empty() { + return true + } + base := p.Rect.Min.Y * p.Stride + i0, i1 := base+p.Rect.Min.X, base+p.Rect.Max.X + for y := p.Rect.Min.Y; y < p.Rect.Max.Y; y++ { + for _, c := range p.Pix[i0:i1] { + if c.A != 0xffff { + return false } } + i0 += p.Stride + i1 += p.Stride } return true } // NewRGBA64 returns a new RGBA64 with the given width and height. func NewRGBA64(w, h int) *RGBA64 { - buf := make([]RGBA64Color, w*h) - pix := make([][]RGBA64Color, h) - for y := range pix { - pix[y] = buf[w*y : w*(y+1)] - } - return &RGBA64{pix} + pix := make([]RGBA64Color, w*h) + return &RGBA64{pix, w, Rectangle{ZP, Point{w, h}}} } -// A NRGBA is an in-memory image backed by a 2-D slice of NRGBAColor values. +// An NRGBA is an in-memory image of NRGBAColor values. type NRGBA struct { - // The Pixel field's indices are y first, then x, so that At(x, y) == Pixel[y][x]. - Pixel [][]NRGBAColor + // Pix holds the image's pixels. The pixel at (x, y) is Pix[y*Stride+x]. + Pix []NRGBAColor + Stride int + // Rect is the image's bounds. + Rect Rectangle } func (p *NRGBA) ColorModel() ColorModel { return NRGBAColorModel } -func (p *NRGBA) Width() int { - if len(p.Pixel) == 0 { - return 0 +func (p *NRGBA) Bounds() Rectangle { return p.Rect } + +func (p *NRGBA) At(x, y int) Color { + if !p.Rect.Contains(Point{x, y}) { + return NRGBAColor{} } - return len(p.Pixel[0]) + return p.Pix[y*p.Stride+x] } -func (p *NRGBA) Height() int { return len(p.Pixel) } - -func (p *NRGBA) At(x, y int) Color { return p.Pixel[y][x] } - -func (p *NRGBA) Set(x, y int, c Color) { p.Pixel[y][x] = toNRGBAColor(c).(NRGBAColor) } +func (p *NRGBA) Set(x, y int, c Color) { + if !p.Rect.Contains(Point{x, y}) { + return + } + p.Pix[y*p.Stride+x] = toNRGBAColor(c).(NRGBAColor) +} // Opaque scans the entire image and returns whether or not it is fully opaque. func (p *NRGBA) Opaque() bool { - h := len(p.Pixel) - if h > 0 { - w := len(p.Pixel[0]) - for y := 0; y < h; y++ { - pix := p.Pixel[y] - for x := 0; x < w; x++ { - if pix[x].A != 0xff { - return false - } + if p.Rect.Empty() { + return true + } + base := p.Rect.Min.Y * p.Stride + i0, i1 := base+p.Rect.Min.X, base+p.Rect.Max.X + for y := p.Rect.Min.Y; y < p.Rect.Max.Y; y++ { + for _, c := range p.Pix[i0:i1] { + if c.A != 0xff { + return false } } + i0 += p.Stride + i1 += p.Stride } return true } // NewNRGBA returns a new NRGBA with the given width and height. func NewNRGBA(w, h int) *NRGBA { - buf := make([]NRGBAColor, w*h) - pix := make([][]NRGBAColor, h) - for y := range pix { - pix[y] = buf[w*y : w*(y+1)] - } - return &NRGBA{pix} + pix := make([]NRGBAColor, w*h) + return &NRGBA{pix, w, Rectangle{ZP, Point{w, h}}} } -// A NRGBA64 is an in-memory image backed by a 2-D slice of NRGBA64Color values. +// An NRGBA64 is an in-memory image of NRGBA64Color values. type NRGBA64 struct { - // The Pixel field's indices are y first, then x, so that At(x, y) == Pixel[y][x]. - Pixel [][]NRGBA64Color + // Pix holds the image's pixels. The pixel at (x, y) is Pix[y*Stride+x]. + Pix []NRGBA64Color + Stride int + // Rect is the image's bounds. + Rect Rectangle } func (p *NRGBA64) ColorModel() ColorModel { return NRGBA64ColorModel } -func (p *NRGBA64) Width() int { - if len(p.Pixel) == 0 { - return 0 +func (p *NRGBA64) Bounds() Rectangle { return p.Rect } + +func (p *NRGBA64) At(x, y int) Color { + if !p.Rect.Contains(Point{x, y}) { + return NRGBA64Color{} } - return len(p.Pixel[0]) + return p.Pix[y*p.Stride+x] } -func (p *NRGBA64) Height() int { return len(p.Pixel) } - -func (p *NRGBA64) At(x, y int) Color { return p.Pixel[y][x] } - -func (p *NRGBA64) Set(x, y int, c Color) { p.Pixel[y][x] = toNRGBA64Color(c).(NRGBA64Color) } +func (p *NRGBA64) Set(x, y int, c Color) { + if !p.Rect.Contains(Point{x, y}) { + return + } + p.Pix[y*p.Stride+x] = toNRGBA64Color(c).(NRGBA64Color) +} // Opaque scans the entire image and returns whether or not it is fully opaque. func (p *NRGBA64) Opaque() bool { - h := len(p.Pixel) - if h > 0 { - w := len(p.Pixel[0]) - for y := 0; y < h; y++ { - pix := p.Pixel[y] - for x := 0; x < w; x++ { - if pix[x].A != 0xffff { - return false - } + if p.Rect.Empty() { + return true + } + base := p.Rect.Min.Y * p.Stride + i0, i1 := base+p.Rect.Min.X, base+p.Rect.Max.X + for y := p.Rect.Min.Y; y < p.Rect.Max.Y; y++ { + for _, c := range p.Pix[i0:i1] { + if c.A != 0xffff { + return false } } + i0 += p.Stride + i1 += p.Stride } return true } // NewNRGBA64 returns a new NRGBA64 with the given width and height. func NewNRGBA64(w, h int) *NRGBA64 { - buf := make([]NRGBA64Color, w*h) - pix := make([][]NRGBA64Color, h) - for y := range pix { - pix[y] = buf[w*y : w*(y+1)] - } - return &NRGBA64{pix} + pix := make([]NRGBA64Color, w*h) + return &NRGBA64{pix, w, Rectangle{ZP, Point{w, h}}} } -// An Alpha is an in-memory image backed by a 2-D slice of AlphaColor values. +// An Alpha is an in-memory image of AlphaColor values. type Alpha struct { - // The Pixel field's indices are y first, then x, so that At(x, y) == Pixel[y][x]. - Pixel [][]AlphaColor + // Pix holds the image's pixels. The pixel at (x, y) is Pix[y*Stride+x]. + Pix []AlphaColor + Stride int + // Rect is the image's bounds. + Rect Rectangle } func (p *Alpha) ColorModel() ColorModel { return AlphaColorModel } -func (p *Alpha) Width() int { - if len(p.Pixel) == 0 { - return 0 +func (p *Alpha) Bounds() Rectangle { return p.Rect } + +func (p *Alpha) At(x, y int) Color { + if !p.Rect.Contains(Point{x, y}) { + return AlphaColor{} } - return len(p.Pixel[0]) + return p.Pix[y*p.Stride+x] } -func (p *Alpha) Height() int { return len(p.Pixel) } - -func (p *Alpha) At(x, y int) Color { return p.Pixel[y][x] } - -func (p *Alpha) Set(x, y int, c Color) { p.Pixel[y][x] = toAlphaColor(c).(AlphaColor) } +func (p *Alpha) Set(x, y int, c Color) { + if !p.Rect.Contains(Point{x, y}) { + return + } + p.Pix[y*p.Stride+x] = toAlphaColor(c).(AlphaColor) +} // Opaque scans the entire image and returns whether or not it is fully opaque. func (p *Alpha) Opaque() bool { - h := len(p.Pixel) - if h > 0 { - w := len(p.Pixel[0]) - for y := 0; y < h; y++ { - pix := p.Pixel[y] - for x := 0; x < w; x++ { - if pix[x].A != 0xff { - return false - } + if p.Rect.Empty() { + return true + } + base := p.Rect.Min.Y * p.Stride + i0, i1 := base+p.Rect.Min.X, base+p.Rect.Max.X + for y := p.Rect.Min.Y; y < p.Rect.Max.Y; y++ { + for _, c := range p.Pix[i0:i1] { + if c.A != 0xff { + return false } } + i0 += p.Stride + i1 += p.Stride } return true } // NewAlpha returns a new Alpha with the given width and height. func NewAlpha(w, h int) *Alpha { - buf := make([]AlphaColor, w*h) - pix := make([][]AlphaColor, h) - for y := range pix { - pix[y] = buf[w*y : w*(y+1)] - } - return &Alpha{pix} + pix := make([]AlphaColor, w*h) + return &Alpha{pix, w, Rectangle{ZP, Point{w, h}}} } -// An Alpha16 is an in-memory image backed by a 2-D slice of Alpha16Color values. +// An Alpha16 is an in-memory image of Alpha16Color values. type Alpha16 struct { - // The Pixel field's indices are y first, then x, so that At(x, y) == Pixel[y][x]. - Pixel [][]Alpha16Color + // Pix holds the image's pixels. The pixel at (x, y) is Pix[y*Stride+x]. + Pix []Alpha16Color + Stride int + // Rect is the image's bounds. + Rect Rectangle } func (p *Alpha16) ColorModel() ColorModel { return Alpha16ColorModel } -func (p *Alpha16) Width() int { - if len(p.Pixel) == 0 { - return 0 +func (p *Alpha16) Bounds() Rectangle { return p.Rect } + +func (p *Alpha16) At(x, y int) Color { + if !p.Rect.Contains(Point{x, y}) { + return Alpha16Color{} } - return len(p.Pixel[0]) + return p.Pix[y*p.Stride+x] } -func (p *Alpha16) Height() int { return len(p.Pixel) } - -func (p *Alpha16) At(x, y int) Color { return p.Pixel[y][x] } - -func (p *Alpha16) Set(x, y int, c Color) { p.Pixel[y][x] = toAlpha16Color(c).(Alpha16Color) } +func (p *Alpha16) Set(x, y int, c Color) { + if !p.Rect.Contains(Point{x, y}) { + return + } + p.Pix[y*p.Stride+x] = toAlpha16Color(c).(Alpha16Color) +} // Opaque scans the entire image and returns whether or not it is fully opaque. func (p *Alpha16) Opaque() bool { - h := len(p.Pixel) - if h > 0 { - w := len(p.Pixel[0]) - for y := 0; y < h; y++ { - pix := p.Pixel[y] - for x := 0; x < w; x++ { - if pix[x].A != 0xffff { - return false - } + if p.Rect.Empty() { + return true + } + base := p.Rect.Min.Y * p.Stride + i0, i1 := base+p.Rect.Min.X, base+p.Rect.Max.X + for y := p.Rect.Min.Y; y < p.Rect.Max.Y; y++ { + for _, c := range p.Pix[i0:i1] { + if c.A != 0xffff { + return false } } + i0 += p.Stride + i1 += p.Stride } return true } // NewAlpha16 returns a new Alpha16 with the given width and height. func NewAlpha16(w, h int) *Alpha16 { - buf := make([]Alpha16Color, w*h) - pix := make([][]Alpha16Color, h) - for y := range pix { - pix[y] = buf[w*y : w*(y+1)] + pix := make([]Alpha16Color, w*h) + return &Alpha16{pix, w, Rectangle{ZP, Point{w, h}}} +} + +// A Gray is an in-memory image of GrayColor values. +type Gray struct { + // Pix holds the image's pixels. The pixel at (x, y) is Pix[y*Stride+x]. + Pix []GrayColor + Stride int + // Rect is the image's bounds. + Rect Rectangle +} + +func (p *Gray) ColorModel() ColorModel { return GrayColorModel } + +func (p *Gray) Bounds() Rectangle { return p.Rect } + +func (p *Gray) At(x, y int) Color { + if !p.Rect.Contains(Point{x, y}) { + return GrayColor{} } - return &Alpha16{pix} + return p.Pix[y*p.Stride+x] +} + +func (p *Gray) Set(x, y int, c Color) { + if !p.Rect.Contains(Point{x, y}) { + return + } + p.Pix[y*p.Stride+x] = toGrayColor(c).(GrayColor) +} + +// Opaque scans the entire image and returns whether or not it is fully opaque. +func (p *Gray) Opaque() bool { + return true +} + +// NewGray returns a new Gray with the given width and height. +func NewGray(w, h int) *Gray { + pix := make([]GrayColor, w*h) + return &Gray{pix, w, Rectangle{ZP, Point{w, h}}} +} + +// A Gray16 is an in-memory image of Gray16Color values. +type Gray16 struct { + // Pix holds the image's pixels. The pixel at (x, y) is Pix[y*Stride+x]. + Pix []Gray16Color + Stride int + // Rect is the image's bounds. + Rect Rectangle +} + +func (p *Gray16) ColorModel() ColorModel { return Gray16ColorModel } + +func (p *Gray16) Bounds() Rectangle { return p.Rect } + +func (p *Gray16) At(x, y int) Color { + if !p.Rect.Contains(Point{x, y}) { + return Gray16Color{} + } + return p.Pix[y*p.Stride+x] +} + +func (p *Gray16) Set(x, y int, c Color) { + if !p.Rect.Contains(Point{x, y}) { + return + } + p.Pix[y*p.Stride+x] = toGray16Color(c).(Gray16Color) +} + +// Opaque scans the entire image and returns whether or not it is fully opaque. +func (p *Gray16) Opaque() bool { + return true +} + +// NewGray16 returns a new Gray16 with the given width and height. +func NewGray16(w, h int) *Gray16 { + pix := make([]Gray16Color, w*h) + return &Gray16{pix, w, Rectangle{ZP, Point{w, h}}} } // A PalettedColorModel represents a fixed palette of colors. @@ -342,30 +451,41 @@ func (p PalettedColorModel) Convert(c Color) Color { // A Paletted is an in-memory image backed by a 2-D slice of uint8 values and a PalettedColorModel. type Paletted struct { - // The Pixel field's indices are y first, then x, so that At(x, y) == Palette[Pixel[y][x]]. - Pixel [][]uint8 + // Pix holds the image's pixels. The pixel at (x, y) is Pix[y*Stride+x]. + Pix []uint8 + Stride int + // Rect is the image's bounds. + Rect Rectangle + // Palette is the image's palette. Palette PalettedColorModel } func (p *Paletted) ColorModel() ColorModel { return p.Palette } -func (p *Paletted) Width() int { - if len(p.Pixel) == 0 { - return 0 +func (p *Paletted) Bounds() Rectangle { return p.Rect } + +func (p *Paletted) At(x, y int) Color { + if len(p.Palette) == 0 { + return nil + } + if !p.Rect.Contains(Point{x, y}) { + return p.Palette[0] } - return len(p.Pixel[0]) + return p.Palette[p.Pix[y*p.Stride+x]] } -func (p *Paletted) Height() int { return len(p.Pixel) } - -func (p *Paletted) At(x, y int) Color { return p.Palette[p.Pixel[y][x]] } - func (p *Paletted) ColorIndexAt(x, y int) uint8 { - return p.Pixel[y][x] + if !p.Rect.Contains(Point{x, y}) { + return 0 + } + return p.Pix[y*p.Stride+x] } func (p *Paletted) SetColorIndex(x, y int, index uint8) { - p.Pixel[y][x] = index + if !p.Rect.Contains(Point{x, y}) { + return + } + p.Pix[y*p.Stride+x] = index } // Opaque scans the entire image and returns whether or not it is fully opaque. @@ -381,10 +501,6 @@ func (p *Paletted) Opaque() bool { // NewPaletted returns a new Paletted with the given width, height and palette. func NewPaletted(w, h int, m PalettedColorModel) *Paletted { - buf := make([]uint8, w*h) - pix := make([][]uint8, h) - for y := range pix { - pix[y] = buf[w*y : w*(y+1)] - } - return &Paletted{pix, m} + pix := make([]uint8, w*h) + return &Paletted{pix, w, Rectangle{ZP, Point{w, h}}, m} } diff --git a/src/pkg/image/jpeg/Makefile b/src/pkg/image/jpeg/Makefile index c84811d6a..5c5f97e71 100644 --- a/src/pkg/image/jpeg/Makefile +++ b/src/pkg/image/jpeg/Makefile @@ -2,7 +2,7 @@ # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. -include $(GOROOT)/src/Make.$(GOARCH) +include ../../../Make.inc TARG=image/jpeg GOFILES=\ @@ -10,4 +10,4 @@ GOFILES=\ idct.go\ reader.go\ -include $(GOROOT)/src/Make.pkg +include ../../../Make.pkg diff --git a/src/pkg/image/jpeg/reader.go b/src/pkg/image/jpeg/reader.go index ec036ef4d..fb9cb11bb 100644 --- a/src/pkg/image/jpeg/reader.go +++ b/src/pkg/image/jpeg/reader.go @@ -147,7 +147,6 @@ func (d *decoder) processSOF(n int) os.Error { } } } - d.image = image.NewRGBA(d.width, d.height) return nil } @@ -206,7 +205,7 @@ func (d *decoder) calcPixel(px, py, lumaBlock, lumaIndex, chromaIndex int) { } else if b > 255 { b = 255 } - d.image.Pixel[py][px] = image.RGBAColor{uint8(r), uint8(g), uint8(b), 0xff} + d.image.Pix[py*d.image.Stride+px] = image.RGBAColor{uint8(r), uint8(g), uint8(b), 0xff} } // Convert the MCU from YCbCr to RGB. @@ -240,7 +239,7 @@ func (d *decoder) convertMCU(mx, my, h0, v0 int) { // Specified in section B.2.3. func (d *decoder) processSOS(n int) os.Error { if d.image == nil { - return FormatError("missing SOF segment") + d.image = image.NewRGBA(d.width, d.height) } if n != 4+2*nComponent { return UnsupportedError("SOS has wrong length") @@ -365,9 +364,8 @@ func (d *decoder) processDRI(n int) os.Error { return nil } -// Decode reads a JPEG formatted image from r and returns it as an image.Image. -func Decode(r io.Reader) (image.Image, os.Error) { - var d decoder +// decode reads a JPEG image from r and returns it as an image.Image. +func (d *decoder) decode(r io.Reader, configOnly bool) (image.Image, os.Error) { if rr, ok := r.(Reader); ok { d.r = rr } else { @@ -411,6 +409,9 @@ func Decode(r io.Reader) (image.Image, os.Error) { switch { case marker == sof0Marker: // Start Of Frame (Baseline). err = d.processSOF(n) + if configOnly { + return nil, err + } case marker == sof2Marker: // Start Of Frame (Progressive). err = UnsupportedError("progressive mode") case marker == dhtMarker: // Define Huffman Table. @@ -432,3 +433,23 @@ func Decode(r io.Reader) (image.Image, os.Error) { } return d.image, nil } + +// Decode reads a JPEG image from r and returns it as an image.Image. +func Decode(r io.Reader) (image.Image, os.Error) { + var d decoder + return d.decode(r, false) +} + +// DecodeConfig returns the color model and dimensions of a JPEG image without +// decoding the entire image. +func DecodeConfig(r io.Reader) (image.Config, os.Error) { + var d decoder + if _, err := d.decode(r, true); err != nil { + return image.Config{}, err + } + return image.Config{image.RGBAColorModel, d.width, d.height}, nil +} + +func init() { + image.RegisterFormat("jpeg", "\xff\xd8", Decode, DecodeConfig) +} diff --git a/src/pkg/image/names.go b/src/pkg/image/names.go index 0b621cff5..c309684ce 100644 --- a/src/pkg/image/names.go +++ b/src/pkg/image/names.go @@ -4,53 +4,64 @@ package image -// Colors from the HTML 4.01 specification: http://www.w3.org/TR/REC-html40/types.html#h-6.5 -// These names do not necessarily match those from other lists, such as the X11 color names. var ( - Aqua = ColorImage{RGBAColor{0x00, 0xff, 0xff, 0xff}} - Black = ColorImage{RGBAColor{0x00, 0x00, 0x00, 0xff}} - Blue = ColorImage{RGBAColor{0x00, 0x00, 0xff, 0xff}} - Fuchsia = ColorImage{RGBAColor{0xff, 0x00, 0xff, 0xff}} - Gray = ColorImage{RGBAColor{0x80, 0x80, 0x80, 0xff}} - Green = ColorImage{RGBAColor{0x00, 0x80, 0x00, 0xff}} - Lime = ColorImage{RGBAColor{0x00, 0xff, 0x00, 0xff}} - Maroon = ColorImage{RGBAColor{0x80, 0x00, 0x00, 0xff}} - Navy = ColorImage{RGBAColor{0x00, 0x00, 0x80, 0xff}} - Olive = ColorImage{RGBAColor{0x80, 0x80, 0x00, 0xff}} - Red = ColorImage{RGBAColor{0xff, 0x00, 0x00, 0xff}} - Purple = ColorImage{RGBAColor{0x80, 0x00, 0x80, 0xff}} - Silver = ColorImage{RGBAColor{0xc0, 0xc0, 0xc0, 0xff}} - Teal = ColorImage{RGBAColor{0x00, 0x80, 0x80, 0xff}} - White = ColorImage{RGBAColor{0xff, 0xff, 0xff, 0xff}} - Yellow = ColorImage{RGBAColor{0xff, 0xff, 0x00, 0xff}} - - // These synonyms are not in HTML 4.01. - Cyan = Aqua - Magenta = Fuchsia + // Black is an opaque black ColorImage. + Black = NewColorImage(Gray16Color{0}) + // White is an opaque white ColorImage. + White = NewColorImage(Gray16Color{0xffff}) + // Transparent is a fully transparent ColorImage. + Transparent = NewColorImage(Alpha16Color{0}) + // Opaque is a fully opaque ColorImage. + Opaque = NewColorImage(Alpha16Color{0xffff}) ) -// A ColorImage is a practically infinite-sized Image of uniform Color. +// A ColorImage is an infinite-sized Image of uniform Color. // It implements both the Color and Image interfaces. type ColorImage struct { C Color } -func (c ColorImage) RGBA() (r, g, b, a uint32) { +func (c *ColorImage) RGBA() (r, g, b, a uint32) { return c.C.RGBA() } -func (c ColorImage) ColorModel() ColorModel { +func (c *ColorImage) ColorModel() ColorModel { return ColorModelFunc(func(Color) Color { return c.C }) } -func (c ColorImage) Width() int { return 1e9 } +func (c *ColorImage) Bounds() Rectangle { return Rectangle{Point{-1e9, -1e9}, Point{1e9, 1e9}} } -func (c ColorImage) Height() int { return 1e9 } - -func (c ColorImage) At(x, y int) Color { return c.C } +func (c *ColorImage) At(x, y int) Color { return c.C } // Opaque scans the entire image and returns whether or not it is fully opaque. -func (c ColorImage) Opaque() bool { +func (c *ColorImage) Opaque() bool { _, _, _, a := c.C.RGBA() return a == 0xffff } + +func NewColorImage(c Color) *ColorImage { + return &ColorImage{c} +} + +// A Tiled is an infinite-sized Image that repeats another Image in both +// directions. Tiled{i, p}.At(x, y) will equal i.At(x+p.X, y+p.Y) for all +// points {x+p.X, y+p.Y} within i's Bounds. +type Tiled struct { + I Image + Offset Point +} + +func (t *Tiled) ColorModel() ColorModel { + return t.I.ColorModel() +} + +func (t *Tiled) Bounds() Rectangle { return Rectangle{Point{-1e9, -1e9}, Point{1e9, 1e9}} } + +func (t *Tiled) At(x, y int) Color { + p := Point{x, y}.Add(t.Offset).Mod(t.I.Bounds()) + return t.I.At(p.X, p.Y) +} + +func NewTiled(i Image, offset Point) *Tiled { + return &Tiled{i, offset} +} diff --git a/src/pkg/image/png/Makefile b/src/pkg/image/png/Makefile index 3ba0f44d3..4101f77e1 100644 --- a/src/pkg/image/png/Makefile +++ b/src/pkg/image/png/Makefile @@ -2,7 +2,7 @@ # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. -include ../../../Make.$(GOARCH) +include ../../../Make.inc TARG=image/png GOFILES=\ diff --git a/src/pkg/image/png/reader.go b/src/pkg/image/png/reader.go index fddb70423..e2d679bb4 100644 --- a/src/pkg/image/png/reader.go +++ b/src/pkg/image/png/reader.go @@ -9,6 +9,7 @@ package png import ( "compress/zlib" + "fmt" "hash" "hash/crc32" "image" @@ -25,6 +26,18 @@ const ( ctTrueColorAlpha = 6 ) +// A cb is a combination of color type and bit depth. +const ( + cbInvalid = iota + cbG8 + cbTC8 + cbP8 + cbTCA8 + cbG16 + cbTC16 + cbTCA16 +) + // Filter type, as per the PNG spec. const ( ftNone = 0 @@ -50,20 +63,25 @@ const ( const pngHeader = "\x89PNG\r\n\x1a\n" +type imgOrErr struct { + img image.Image + err os.Error +} + type decoder struct { width, height int - image image.Image - colorType uint8 + palette image.PalettedColorModel + cb int stage int idatWriter io.WriteCloser - idatDone chan os.Error + idatDone chan imgOrErr tmp [3 * 256]byte } // A FormatError reports that the input is not a valid PNG. type FormatError string -func (e FormatError) String() string { return "invalid PNG format: " + string(e) } +func (e FormatError) String() string { return "png: invalid format: " + string(e) } var chunkOrderError = FormatError("chunk out of order") @@ -72,12 +90,12 @@ type IDATDecodingError struct { Err os.Error } -func (e IDATDecodingError) String() string { return "IDAT decoding error: " + e.Err.String() } +func (e IDATDecodingError) String() string { return "png: IDAT decoding error: " + e.Err.String() } // An UnsupportedError reports that the input uses a valid but unimplemented PNG feature. type UnsupportedError string -func (e UnsupportedError) String() string { return "unsupported PNG feature: " + string(e) } +func (e UnsupportedError) String() string { return "png: unsupported feature: " + string(e) } // Big-endian. func parseUint32(b []uint8) uint32 { @@ -107,9 +125,6 @@ func (d *decoder) parseIHDR(r io.Reader, crc hash.Hash32, length uint32) os.Erro return err } crc.Write(d.tmp[0:13]) - if d.tmp[8] != 8 { - return UnsupportedError("bit depth") - } if d.tmp[10] != 0 || d.tmp[11] != 0 || d.tmp[12] != 0 { return UnsupportedError("compression, filter or interlace method") } @@ -122,16 +137,31 @@ func (d *decoder) parseIHDR(r io.Reader, crc hash.Hash32, length uint32) os.Erro if nPixels != int64(int(nPixels)) { return UnsupportedError("dimension overflow") } - d.colorType = d.tmp[9] - switch d.colorType { - case ctTrueColor: - d.image = image.NewRGBA(int(w), int(h)) - case ctPaletted: - d.image = image.NewPaletted(int(w), int(h), nil) - case ctTrueColorAlpha: - d.image = image.NewNRGBA(int(w), int(h)) - default: - return UnsupportedError("color type") + d.cb = cbInvalid + switch d.tmp[8] { + case 8: + switch d.tmp[9] { + case ctGrayscale: + d.cb = cbG8 + case ctTrueColor: + d.cb = cbTC8 + case ctPaletted: + d.cb = cbP8 + case ctTrueColorAlpha: + d.cb = cbTCA8 + } + case 16: + switch d.tmp[9] { + case ctGrayscale: + d.cb = cbG16 + case ctTrueColor: + d.cb = cbTC16 + case ctTrueColorAlpha: + d.cb = cbTCA16 + } + } + if d.cb == cbInvalid { + return UnsupportedError(fmt.Sprintf("bit depth %d, color type %d", d.tmp[8], d.tmp[9])) } d.width, d.height = int(w), int(h) return nil @@ -147,17 +177,15 @@ func (d *decoder) parsePLTE(r io.Reader, crc hash.Hash32, length uint32) os.Erro return err } crc.Write(d.tmp[0:n]) - switch d.colorType { - case ctPaletted: - palette := make([]image.Color, np) + switch d.cb { + case cbP8: + d.palette = image.PalettedColorModel(make([]image.Color, np)) for i := 0; i < np; i++ { - palette[i] = image.RGBAColor{d.tmp[3*i+0], d.tmp[3*i+1], d.tmp[3*i+2], 0xff} + d.palette[i] = image.RGBAColor{d.tmp[3*i+0], d.tmp[3*i+1], d.tmp[3*i+2], 0xff} } - d.image.(*image.Paletted).Palette = image.PalettedColorModel(palette) - case ctTrueColor, ctTrueColorAlpha: + case cbTC8, cbTCA8, cbTC16, cbTCA16: // As per the PNG spec, a PLTE chunk is optional (and for practical purposes, // ignorable) for the ctTrueColor and ctTrueColorAlpha color types (section 4.1.2). - return nil default: return FormatError("PLTE, color type mismatch") } @@ -173,19 +201,20 @@ func (d *decoder) parsetRNS(r io.Reader, crc hash.Hash32, length uint32) os.Erro return err } crc.Write(d.tmp[0:n]) - switch d.colorType { - case ctTrueColor: - return UnsupportedError("TrueColor transparency") - case ctPaletted: - p := d.image.(*image.Paletted).Palette - if n > len(p) { + switch d.cb { + case cbG8, cbG16: + return UnsupportedError("grayscale transparency") + case cbTC8, cbTC16: + return UnsupportedError("truecolor transparency") + case cbP8: + if n > len(d.palette) { return FormatError("bad tRNS length") } for i := 0; i < n; i++ { - rgba := p[i].(image.RGBAColor) - p[i] = image.RGBAColor{rgba.R, rgba.G, rgba.B, d.tmp[i]} + rgba := d.palette[i].(image.RGBAColor) + d.palette[i] = image.RGBAColor{rgba.R, rgba.G, rgba.B, d.tmp[i]} } - case ctTrueColorAlpha: + case cbTCA8, cbTCA16: return FormatError("tRNS, color type mismatch") } return nil @@ -205,30 +234,54 @@ func paeth(a, b, c uint8) uint8 { return c } -func (d *decoder) idatReader(idat io.Reader) os.Error { +func (d *decoder) idatReader(idat io.Reader) (image.Image, os.Error) { r, err := zlib.NewReader(idat) if err != nil { - return err + return nil, err } defer r.Close() bpp := 0 // Bytes per pixel. maxPalette := uint8(0) var ( + gray *image.Gray rgba *image.RGBA - nrgba *image.NRGBA paletted *image.Paletted + nrgba *image.NRGBA + gray16 *image.Gray16 + rgba64 *image.RGBA64 + nrgba64 *image.NRGBA64 + img image.Image ) - switch d.colorType { - case ctTrueColor: + switch d.cb { + case cbG8: + bpp = 1 + gray = image.NewGray(d.width, d.height) + img = gray + case cbTC8: bpp = 3 - rgba = d.image.(*image.RGBA) - case ctPaletted: + rgba = image.NewRGBA(d.width, d.height) + img = rgba + case cbP8: bpp = 1 - paletted = d.image.(*image.Paletted) - maxPalette = uint8(len(paletted.Palette) - 1) - case ctTrueColorAlpha: + paletted = image.NewPaletted(d.width, d.height, d.palette) + img = paletted + maxPalette = uint8(len(d.palette) - 1) + case cbTCA8: bpp = 4 - nrgba = d.image.(*image.NRGBA) + nrgba = image.NewNRGBA(d.width, d.height) + img = nrgba + case cbG16: + bpp = 2 + gray16 = image.NewGray16(d.width, d.height) + img = gray16 + case cbTC16: + bpp = 6 + rgba64 = image.NewRGBA64(d.width, d.height) + img = rgba64 + case cbTCA16: + bpp = 8 + nrgba64 = image.NewNRGBA64(d.width, d.height) + img = nrgba64 } // cr and pr are the bytes for the current and previous row. // The +1 is for the per-row filter type, which is at cr[0]. @@ -239,7 +292,7 @@ func (d *decoder) idatReader(idat io.Reader) os.Error { // Read the decompressed bytes. _, err := io.ReadFull(r, cr) if err != nil { - return err + return nil, err } // Apply the filter. @@ -271,32 +324,56 @@ func (d *decoder) idatReader(idat io.Reader) os.Error { cdat[i] += paeth(cdat[i-bpp], pdat[i], pdat[i-bpp]) } default: - return FormatError("bad filter type") + return nil, FormatError("bad filter type") } // Convert from bytes to colors. - switch d.colorType { - case ctTrueColor: + switch d.cb { + case cbG8: + for x := 0; x < d.width; x++ { + gray.Set(x, y, image.GrayColor{cdat[x]}) + } + case cbTC8: for x := 0; x < d.width; x++ { rgba.Set(x, y, image.RGBAColor{cdat[3*x+0], cdat[3*x+1], cdat[3*x+2], 0xff}) } - case ctPaletted: + case cbP8: for x := 0; x < d.width; x++ { if cdat[x] > maxPalette { - return FormatError("palette index out of range") + return nil, FormatError("palette index out of range") } paletted.SetColorIndex(x, y, cdat[x]) } - case ctTrueColorAlpha: + case cbTCA8: for x := 0; x < d.width; x++ { nrgba.Set(x, y, image.NRGBAColor{cdat[4*x+0], cdat[4*x+1], cdat[4*x+2], cdat[4*x+3]}) } + case cbG16: + for x := 0; x < d.width; x++ { + ycol := uint16(cdat[2*x+0])<<8 | uint16(cdat[2*x+1]) + gray16.Set(x, y, image.Gray16Color{ycol}) + } + case cbTC16: + for x := 0; x < d.width; x++ { + rcol := uint16(cdat[6*x+0])<<8 | uint16(cdat[6*x+1]) + gcol := uint16(cdat[6*x+2])<<8 | uint16(cdat[6*x+3]) + bcol := uint16(cdat[6*x+4])<<8 | uint16(cdat[6*x+5]) + rgba64.Set(x, y, image.RGBA64Color{rcol, gcol, bcol, 0xffff}) + } + case cbTCA16: + for x := 0; x < d.width; x++ { + rcol := uint16(cdat[8*x+0])<<8 | uint16(cdat[8*x+1]) + gcol := uint16(cdat[8*x+2])<<8 | uint16(cdat[8*x+3]) + bcol := uint16(cdat[8*x+4])<<8 | uint16(cdat[8*x+5]) + acol := uint16(cdat[8*x+6])<<8 | uint16(cdat[8*x+7]) + nrgba64.Set(x, y, image.NRGBA64Color{rcol, gcol, bcol, acol}) + } } // The current row for y is the previous row for y+1. pr, cr = cr, pr } - return nil + return img, nil } func (d *decoder) parseIDAT(r io.Reader, crc hash.Hash32, length uint32) os.Error { @@ -308,14 +385,14 @@ func (d *decoder) parseIDAT(r io.Reader, crc hash.Hash32, length uint32) os.Erro if d.idatWriter == nil { pr, pw := io.Pipe() d.idatWriter = pw - d.idatDone = make(chan os.Error) + d.idatDone = make(chan imgOrErr) go func() { - err := d.idatReader(pr) + img, err := d.idatReader(pr) if err == os.EOF { err = FormatError("too little IDAT") } pr.CloseWithError(FormatError("too much IDAT")) - d.idatDone <- err + d.idatDone <- imgOrErr{img, err} }() } var buf [4096]byte @@ -386,7 +463,7 @@ func (d *decoder) parseChunk(r io.Reader) os.Error { } err = d.parsetRNS(r, crc, length) case "IDAT": - if d.stage < dsSeenIHDR || d.stage > dsSeenIDAT || (d.colorType == ctPaletted && d.stage == dsSeenIHDR) { + if d.stage < dsSeenIHDR || d.stage > dsSeenIDAT || (d.cb == cbP8 && d.stage == dsSeenIHDR) { return chunkOrderError } d.stage = dsSeenIDAT @@ -438,7 +515,7 @@ func (d *decoder) checkHeader(r io.Reader) os.Error { return nil } -// Decode reads a PNG formatted image from r and returns it as an image.Image. +// Decode reads a PNG image from r and returns it as an image.Image. // The type of Image returned depends on the PNG contents. func Decode(r io.Reader) (image.Image, os.Error) { var d decoder @@ -446,21 +523,66 @@ func Decode(r io.Reader) (image.Image, os.Error) { if err != nil { return nil, err } - for d.stage = dsStart; d.stage != dsSeenIEND; { + for d.stage != dsSeenIEND { err = d.parseChunk(r) if err != nil { break } } + var img image.Image if d.idatWriter != nil { d.idatWriter.Close() - err1 := <-d.idatDone + ie := <-d.idatDone if err == nil { - err = err1 + img, err = ie.img, ie.err } } if err != nil { return nil, err } - return d.image, nil + return img, nil +} + +// DecodeConfig returns the color model and dimensions of a PNG image without +// decoding the entire image. +func DecodeConfig(r io.Reader) (image.Config, os.Error) { + var d decoder + err := d.checkHeader(r) + if err != nil { + return image.Config{}, err + } + for { + err = d.parseChunk(r) + if err != nil { + return image.Config{}, err + } + if d.stage == dsSeenIHDR && d.cb != cbP8 { + break + } + if d.stage == dsSeenPLTE && d.cb == cbP8 { + break + } + } + var cm image.ColorModel + switch d.cb { + case cbG8: + cm = image.GrayColorModel + case cbTC8: + cm = image.RGBAColorModel + case cbP8: + cm = d.palette + case cbTCA8: + cm = image.NRGBAColorModel + case cbG16: + cm = image.Gray16ColorModel + case cbTC16: + cm = image.RGBA64ColorModel + case cbTCA16: + cm = image.NRGBA64ColorModel + } + return image.Config{cm, d.width, d.height}, nil +} + +func init() { + image.RegisterFormat("png", pngHeader, Decode, DecodeConfig) } diff --git a/src/pkg/image/png/reader_test.go b/src/pkg/image/png/reader_test.go index 1dc45992e..fefceee3a 100644 --- a/src/pkg/image/png/reader_test.go +++ b/src/pkg/image/png/reader_test.go @@ -14,23 +14,24 @@ import ( ) // The go PNG library currently supports only a subset of the full PNG specification. -// In particular, bit depths other than 8 are not supported, and neither are grayscale images. +// In particular, bit depths other than 8 or 16 are not supported, nor are grayscale- +// alpha images. var filenames = []string{ - //"basn0g01", // bit depth is not 8 - //"basn0g02", // bit depth is not 8 - //"basn0g04", // bit depth is not 8 - //"basn0g08", // grayscale color model - //"basn0g16", // bit depth is not 8 + //"basn0g01", // bit depth is not 8 or 16 + //"basn0g02", // bit depth is not 8 or 16 + //"basn0g04", // bit depth is not 8 or 16 + "basn0g08", + "basn0g16", "basn2c08", - //"basn2c16", // bit depth is not 8 - //"basn3p01", // bit depth is not 8 - //"basn3p02", // bit depth is not 8 - //"basn3p04", // bit depth is not 8 + "basn2c16", + //"basn3p01", // bit depth is not 8 or 16 + //"basn3p02", // bit depth is not 8 or 16 + //"basn3p04", // bit depth is not 8 or 16 "basn3p08", - //"basn4a08", // grayscale color model - //"basn4a16", // bit depth is not 8 + //"basn4a08", // grayscale-alpha color model + //"basn4a16", // grayscale-alpha color model "basn6a08", - //"basn6a16", // bit depth is not 8 + "basn6a16", } func readPng(filename string) (image.Image, os.Error) { @@ -45,23 +46,34 @@ func readPng(filename string) (image.Image, os.Error) { // An approximation of the sng command-line tool. func sng(w io.WriteCloser, filename string, png image.Image) { defer w.Close() - // For now, the go PNG parser only reads bitdepths of 8. - bitdepth := 8 + bounds := png.Bounds() + cm := png.ColorModel() + var bitdepth int + switch cm { + case image.RGBAColorModel, image.NRGBAColorModel, image.AlphaColorModel, image.GrayColorModel: + bitdepth = 8 + default: + bitdepth = 16 + } + cpm, _ := cm.(image.PalettedColorModel) + var paletted *image.Paletted + if cpm != nil { + bitdepth = 8 + paletted = png.(*image.Paletted) + } // Write the filename and IHDR. io.WriteString(w, "#SNG: from "+filename+".png\nIHDR {\n") - fmt.Fprintf(w, " width: %d; height: %d; bitdepth: %d;\n", png.Width(), png.Height(), bitdepth) - cm := png.ColorModel() - var paletted *image.Paletted - cpm, _ := cm.(image.PalettedColorModel) + fmt.Fprintf(w, " width: %d; height: %d; bitdepth: %d;\n", bounds.Dx(), bounds.Dy(), bitdepth) switch { - case cm == image.RGBAColorModel: + case cm == image.RGBAColorModel, cm == image.RGBA64ColorModel: io.WriteString(w, " using color;\n") - case cm == image.NRGBAColorModel: + case cm == image.NRGBAColorModel, cm == image.NRGBA64ColorModel: io.WriteString(w, " using color alpha;\n") + case cm == image.GrayColorModel, cm == image.Gray16ColorModel: + io.WriteString(w, " using grayscale;\n") case cpm != nil: io.WriteString(w, " using color palette;\n") - paletted = png.(*image.Paletted) default: io.WriteString(w, "unknown PNG decoder color model\n") } @@ -86,20 +98,40 @@ func sng(w io.WriteCloser, filename string, png image.Image) { // Write the IMAGE. io.WriteString(w, "IMAGE {\n pixels hex\n") - for y := 0; y < png.Height(); y++ { + for y := bounds.Min.Y; y < bounds.Max.Y; y++ { switch { + case cm == image.GrayColorModel: + for x := bounds.Min.X; x < bounds.Max.X; x++ { + gray := png.At(x, y).(image.GrayColor) + fmt.Fprintf(w, "%02x", gray.Y) + } + case cm == image.Gray16ColorModel: + for x := bounds.Min.X; x < bounds.Max.X; x++ { + gray16 := png.At(x, y).(image.Gray16Color) + fmt.Fprintf(w, "%04x ", gray16.Y) + } case cm == image.RGBAColorModel: - for x := 0; x < png.Width(); x++ { + for x := bounds.Min.X; x < bounds.Max.X; x++ { rgba := png.At(x, y).(image.RGBAColor) fmt.Fprintf(w, "%02x%02x%02x ", rgba.R, rgba.G, rgba.B) } + case cm == image.RGBA64ColorModel: + for x := bounds.Min.X; x < bounds.Max.X; x++ { + rgba64 := png.At(x, y).(image.RGBA64Color) + fmt.Fprintf(w, "%04x%04x%04x ", rgba64.R, rgba64.G, rgba64.B) + } case cm == image.NRGBAColorModel: - for x := 0; x < png.Width(); x++ { + for x := bounds.Min.X; x < bounds.Max.X; x++ { nrgba := png.At(x, y).(image.NRGBAColor) fmt.Fprintf(w, "%02x%02x%02x%02x ", nrgba.R, nrgba.G, nrgba.B, nrgba.A) } + case cm == image.NRGBA64ColorModel: + for x := bounds.Min.X; x < bounds.Max.X; x++ { + nrgba64 := png.At(x, y).(image.NRGBA64Color) + fmt.Fprintf(w, "%04x%04x%04x%04x ", nrgba64.R, nrgba64.G, nrgba64.B, nrgba64.A) + } case cpm != nil: - for x := 0; x < png.Width(); x++ { + for x := bounds.Min.X; x < bounds.Max.X; x++ { fmt.Fprintf(w, "%02x", paletted.ColorIndexAt(x, y)) } } diff --git a/src/pkg/image/png/writer.go b/src/pkg/image/png/writer.go index e186ca819..081d06bf5 100644 --- a/src/pkg/image/png/writer.go +++ b/src/pkg/image/png/writer.go @@ -15,13 +15,13 @@ import ( ) type encoder struct { - w io.Writer - m image.Image - colorType uint8 - err os.Error - header [8]byte - footer [4]byte - tmp [3 * 256]byte + w io.Writer + m image.Image + cb int + err os.Error + header [8]byte + footer [4]byte + tmp [3 * 256]byte } // Big-endian. @@ -32,10 +32,18 @@ func writeUint32(b []uint8, u uint32) { b[3] = uint8(u >> 0) } +type opaquer interface { + Opaque() bool +} + // Returns whether or not the image is fully opaque. func opaque(m image.Image) bool { - for y := 0; y < m.Height(); y++ { - for x := 0; x < m.Width(); x++ { + if o, ok := m.(opaquer); ok { + return o.Opaque() + } + b := m.Bounds() + for y := b.Min.Y; y < b.Max.Y; y++ { + for x := b.Min.X; x < b.Max.X; x++ { _, _, _, a := m.At(x, y).RGBA() if a != 0xffff { return false @@ -84,10 +92,33 @@ func (e *encoder) writeChunk(b []byte, name string) { } func (e *encoder) writeIHDR() { - writeUint32(e.tmp[0:4], uint32(e.m.Width())) - writeUint32(e.tmp[4:8], uint32(e.m.Height())) - e.tmp[8] = 8 // bit depth - e.tmp[9] = e.colorType + b := e.m.Bounds() + writeUint32(e.tmp[0:4], uint32(b.Dx())) + writeUint32(e.tmp[4:8], uint32(b.Dy())) + // Set bit depth and color type. + switch e.cb { + case cbG8: + e.tmp[8] = 8 + e.tmp[9] = ctGrayscale + case cbTC8: + e.tmp[8] = 8 + e.tmp[9] = ctTrueColor + case cbP8: + e.tmp[8] = 8 + e.tmp[9] = ctPaletted + case cbTCA8: + e.tmp[8] = 8 + e.tmp[9] = ctTrueColorAlpha + case cbG16: + e.tmp[8] = 16 + e.tmp[9] = ctGrayscale + case cbTC16: + e.tmp[8] = 16 + e.tmp[9] = ctTrueColor + case cbTCA16: + e.tmp[8] = 16 + e.tmp[9] = ctTrueColorAlpha + } e.tmp[10] = 0 // default compression method e.tmp[11] = 0 // default filter method e.tmp[12] = 0 // non-interlaced @@ -224,7 +255,7 @@ func filter(cr [][]byte, pr []byte, bpp int) int { return filter } -func writeImage(w io.Writer, m image.Image, ct uint8) os.Error { +func writeImage(w io.Writer, m image.Image, cb int) os.Error { zw, err := zlib.NewWriter(w) if err != nil { return err @@ -233,51 +264,94 @@ func writeImage(w io.Writer, m image.Image, ct uint8) os.Error { bpp := 0 // Bytes per pixel. var paletted *image.Paletted - switch ct { - case ctTrueColor: + switch cb { + case cbG8: + bpp = 1 + case cbTC8: bpp = 3 - case ctPaletted: + case cbP8: bpp = 1 paletted = m.(*image.Paletted) - case ctTrueColorAlpha: + case cbTCA8: bpp = 4 + case cbTC16: + bpp = 6 + case cbTCA16: + bpp = 8 + case cbG16: + bpp = 2 } // cr[*] and pr are the bytes for the current and previous row. // cr[0] is unfiltered (or equivalently, filtered with the ftNone filter). // cr[ft], for non-zero filter types ft, are buffers for transforming cr[0] under the // other PNG filter types. These buffers are allocated once and re-used for each row. // The +1 is for the per-row filter type, which is at cr[*][0]. + b := m.Bounds() var cr [nFilter][]uint8 for i := 0; i < len(cr); i++ { - cr[i] = make([]uint8, 1+bpp*m.Width()) + cr[i] = make([]uint8, 1+bpp*b.Dx()) cr[i][0] = uint8(i) } - pr := make([]uint8, 1+bpp*m.Width()) + pr := make([]uint8, 1+bpp*b.Dx()) - for y := 0; y < m.Height(); y++ { + for y := b.Min.Y; y < b.Max.Y; y++ { // Convert from colors to bytes. - switch ct { - case ctTrueColor: - for x := 0; x < m.Width(); x++ { + switch cb { + case cbG8: + for x := b.Min.X; x < b.Max.X; x++ { + c := image.GrayColorModel.Convert(m.At(x, y)).(image.GrayColor) + cr[0][x+1] = c.Y + } + case cbTC8: + for x := b.Min.X; x < b.Max.X; x++ { // We have previously verified that the alpha value is fully opaque. r, g, b, _ := m.At(x, y).RGBA() cr[0][3*x+1] = uint8(r >> 8) cr[0][3*x+2] = uint8(g >> 8) cr[0][3*x+3] = uint8(b >> 8) } - case ctPaletted: - for x := 0; x < m.Width(); x++ { - cr[0][x+1] = paletted.ColorIndexAt(x, y) - } - case ctTrueColorAlpha: + case cbP8: + rowOffset := y * paletted.Stride + copy(cr[0][b.Min.X+1:], paletted.Pix[rowOffset+b.Min.X:rowOffset+b.Max.X]) + case cbTCA8: // Convert from image.Image (which is alpha-premultiplied) to PNG's non-alpha-premultiplied. - for x := 0; x < m.Width(); x++ { + for x := b.Min.X; x < b.Max.X; x++ { c := image.NRGBAColorModel.Convert(m.At(x, y)).(image.NRGBAColor) cr[0][4*x+1] = c.R cr[0][4*x+2] = c.G cr[0][4*x+3] = c.B cr[0][4*x+4] = c.A } + case cbG16: + for x := b.Min.X; x < b.Max.X; x++ { + c := image.Gray16ColorModel.Convert(m.At(x, y)).(image.Gray16Color) + cr[0][2*x+1] = uint8(c.Y >> 8) + cr[0][2*x+2] = uint8(c.Y) + } + case cbTC16: + for x := b.Min.X; x < b.Max.X; x++ { + // We have previously verified that the alpha value is fully opaque. + r, g, b, _ := m.At(x, y).RGBA() + cr[0][6*x+1] = uint8(r >> 8) + cr[0][6*x+2] = uint8(r) + cr[0][6*x+3] = uint8(g >> 8) + cr[0][6*x+4] = uint8(g) + cr[0][6*x+5] = uint8(b >> 8) + cr[0][6*x+6] = uint8(b) + } + case cbTCA16: + // Convert from image.Image (which is alpha-premultiplied) to PNG's non-alpha-premultiplied. + for x := b.Min.X; x < b.Max.X; x++ { + c := image.NRGBA64ColorModel.Convert(m.At(x, y)).(image.NRGBA64Color) + cr[0][8*x+1] = uint8(c.R >> 8) + cr[0][8*x+2] = uint8(c.R) + cr[0][8*x+3] = uint8(c.G >> 8) + cr[0][8*x+4] = uint8(c.G) + cr[0][8*x+5] = uint8(c.B >> 8) + cr[0][8*x+6] = uint8(c.B) + cr[0][8*x+7] = uint8(c.A >> 8) + cr[0][8*x+8] = uint8(c.A) + } } // Apply the filter. @@ -305,7 +379,7 @@ func (e *encoder) writeIDATs() { if e.err != nil { return } - e.err = writeImage(bw, e.m, e.colorType) + e.err = writeImage(bw, e.m, e.cb) if e.err != nil { return } @@ -320,7 +394,7 @@ func Encode(w io.Writer, m image.Image) os.Error { // Obviously, negative widths and heights are invalid. Furthermore, the PNG // spec section 11.2.2 says that zero is invalid. Excessively large images are // also rejected. - mw, mh := int64(m.Width()), int64(m.Height()) + mw, mh := int64(m.Bounds().Dx()), int64(m.Bounds().Dy()) if mw <= 0 || mh <= 0 || mw >= 1<<32 || mh >= 1<<32 { return FormatError("invalid image size: " + strconv.Itoa64(mw) + "x" + strconv.Itoa64(mw)) } @@ -328,12 +402,28 @@ func Encode(w io.Writer, m image.Image) os.Error { var e encoder e.w = w e.m = m - e.colorType = uint8(ctTrueColorAlpha) pal, _ := m.(*image.Paletted) if pal != nil { - e.colorType = ctPaletted - } else if opaque(m) { - e.colorType = ctTrueColor + e.cb = cbP8 + } else { + switch m.ColorModel() { + case image.GrayColorModel: + e.cb = cbG8 + case image.Gray16ColorModel: + e.cb = cbG16 + case image.RGBAColorModel, image.NRGBAColorModel, image.AlphaColorModel: + if opaque(m) { + e.cb = cbTC8 + } else { + e.cb = cbTCA8 + } + default: + if opaque(m) { + e.cb = cbTC16 + } else { + e.cb = cbTCA16 + } + } } _, e.err = io.WriteString(w, pngHeader) diff --git a/src/pkg/image/png/writer_test.go b/src/pkg/image/png/writer_test.go index a61e1c95a..f218a5564 100644 --- a/src/pkg/image/png/writer_test.go +++ b/src/pkg/image/png/writer_test.go @@ -5,6 +5,7 @@ package png import ( + "bytes" "fmt" "image" "io" @@ -13,15 +14,16 @@ import ( ) func diff(m0, m1 image.Image) os.Error { - if m0.Width() != m1.Width() || m0.Height() != m1.Height() { - return os.NewError(fmt.Sprintf("dimensions differ: %dx%d vs %dx%d", m0.Width(), m0.Height(), m1.Width(), m1.Height())) + b0, b1 := m0.Bounds(), m1.Bounds() + if !b0.Eq(b1) { + return fmt.Errorf("dimensions differ: %v vs %v", b0, b1) } - for y := 0; y < m0.Height(); y++ { - for x := 0; x < m0.Width(); x++ { + for y := b0.Min.Y; y < b0.Max.Y; y++ { + for x := b0.Min.X; x < b0.Max.X; x++ { r0, g0, b0, a0 := m0.At(x, y).RGBA() r1, g1, b1, a1 := m1.At(x, y).RGBA() if r0 != r1 || g0 != g1 || b0 != b1 || a0 != a1 { - return os.NewError(fmt.Sprintf("colors differ at (%d, %d): %v vs %v", x, y, m0.At(x, y), m1.At(x, y))) + return fmt.Errorf("colors differ at (%d, %d): %v vs %v", x, y, m0.At(x, y), m1.At(x, y)) } } } @@ -67,3 +69,18 @@ func TestWriter(t *testing.T) { } } } + +func BenchmarkEncodePaletted(b *testing.B) { + b.StopTimer() + img := image.NewPaletted(640, 480, + []image.Color{ + image.RGBAColor{0, 0, 0, 255}, + image.RGBAColor{255, 255, 255, 255}, + }) + b.StartTimer() + buffer := new(bytes.Buffer) + for i := 0; i < b.N; i++ { + buffer.Reset() + Encode(buffer, img) + } +} |