github.com/cellofellow/gopkg@v0.0.0-20140722061823-eec0544a62ad/image/bmp/bmp.go (about)

     1  // Copyright 2014 <chaishushan{AT}gmail.com>. 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.
     4  
     5  // Package bmp implements a BMP image decoder and encoder.
     6  //
     7  // The BMP specification is at http://www.digicamsoft.com/bmp/bmp.html.
     8  package bmp
     9  
    10  import (
    11  	"image"
    12  	"image/color"
    13  	"io"
    14  
    15  	"code.google.com/p/go.image/bmp"
    16  	image_ext "github.com/chai2010/gopkg/image"
    17  	"github.com/chai2010/gopkg/image/convert"
    18  )
    19  
    20  // Options are the encoding and decoding parameters.
    21  type Options struct {
    22  	ColorModel color.Model
    23  }
    24  
    25  // DecodeConfig returns the color model and dimensions of a BMP image without
    26  // decoding the entire image.
    27  // Limitation: The file must be 8 or 24 bits per pixel.
    28  func DecodeConfig(r io.Reader) (config image.Config, err error) {
    29  	return bmp.DecodeConfig(r)
    30  }
    31  
    32  // Decode reads a BMP image from r and returns it as an image.Image.
    33  // Limitation: The file must be 8 or 24 bits per pixel.
    34  func Decode(r io.Reader, opt *Options) (m image.Image, err error) {
    35  	if m, err = bmp.Decode(r); err != nil {
    36  		return
    37  	}
    38  	if opt != nil && opt.ColorModel != nil {
    39  		m = convert.ColorModel(m, opt.ColorModel)
    40  	}
    41  	return
    42  }
    43  
    44  // Encode writes the image m to w in BMP format.
    45  func Encode(w io.Writer, m image.Image, opt *Options) error {
    46  	if opt != nil && opt.ColorModel != nil {
    47  		m = convert.ColorModel(m, opt.ColorModel)
    48  	}
    49  	return bmp.Encode(w, m)
    50  }
    51  
    52  func imageExtDecode(r io.Reader, opt interface{}) (image.Image, error) {
    53  	if opt, ok := opt.(*Options); ok {
    54  		return Decode(r, opt)
    55  	} else {
    56  		return Decode(r, nil)
    57  	}
    58  }
    59  
    60  func imageExtEncode(w io.Writer, m image.Image, opt interface{}) error {
    61  	if opt, ok := opt.(*Options); ok {
    62  		return Encode(w, m, opt)
    63  	} else {
    64  		return Encode(w, m, nil)
    65  	}
    66  }
    67  
    68  func init() {
    69  	image_ext.RegisterFormat(image_ext.Format{
    70  		Name:         "bmp",
    71  		Extensions:   []string{".bmp"},
    72  		Magics:       []string{"BM????\x00\x00\x00\x00"},
    73  		DecodeConfig: DecodeConfig,
    74  		Decode:       imageExtDecode,
    75  		Encode:       imageExtEncode,
    76  	})
    77  }