1 // Copyright 2010 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
13 // ErrFormat indicates that decoding encountered an unknown format.
14 var ErrFormat
= errors
.New("image: unknown format")
16 // A format holds an image format's name, magic header and how to decode it.
19 decode
func(io
.Reader
) (Image
, error
)
20 decodeConfig
func(io
.Reader
) (Config
, error
)
23 // Formats is the list of registered formats.
26 // RegisterFormat registers an image format for use by Decode.
27 // Name is the name of the format, like "jpeg" or "png".
28 // Magic is the magic prefix that identifies the format's encoding. The magic
29 // string can contain "?" wildcards that each match any one byte.
30 // Decode is the function that decodes the encoded image.
31 // DecodeConfig is the function that decodes just its configuration.
32 func RegisterFormat(name
, magic
string, decode
func(io
.Reader
) (Image
, error
), decodeConfig
func(io
.Reader
) (Config
, error
)) {
33 formats
= append(formats
, format
{name
, magic
, decode
, decodeConfig
})
36 // A reader is an io.Reader that can also peek ahead.
37 type reader
interface {
39 Peek(int) ([]byte, error
)
42 // asReader converts an io.Reader to a reader.
43 func asReader(r io
.Reader
) reader
{
44 if rr
, ok
:= r
.(reader
); ok
{
47 return bufio
.NewReader(r
)
50 // Match reports whether magic matches b. Magic may contain "?" wildcards.
51 func match(magic
string, b
[]byte) bool {
52 if len(magic
) != len(b
) {
56 if magic
[i
] != c
&& magic
[i
] != '?' {
63 // Sniff determines the format of r's data.
64 func sniff(r reader
) format
{
65 for _
, f
:= range formats
{
66 b
, err
:= r
.Peek(len(f
.magic
))
67 if err
== nil && match(f
.magic
, b
) {
74 // Decode decodes an image that has been encoded in a registered format.
75 // The string returned is the format name used during format registration.
76 // Format registration is typically done by an init function in the codec-
78 func Decode(r io
.Reader
) (Image
, string, error
) {
82 return nil, "", ErrFormat
84 m
, err
:= f
.decode(rr
)
88 // DecodeConfig decodes the color model and dimensions of an image that has
89 // been encoded in a registered format. The string returned is the format name
90 // used during format registration. Format registration is typically done by
91 // an init function in the codec-specific package.
92 func DecodeConfig(r io
.Reader
) (Config
, string, error
) {
95 if f
.decodeConfig
== nil {
96 return Config
{}, "", ErrFormat
98 c
, err
:= f
.decodeConfig(rr
)