Example #1
// Encode writes an arbitrary image in any of the Netpbm formats.  If opts is
// nil, Encode will default to matching the image format if the image is a
// Netpbm image or producing a raw PPM file with no header comment and a
// maximum color-channel value of 255 for any other image type.
func Encode(w io.Writer, img image.Image, opts *EncodeOptions) error {
	var o EncodeOptions
	if opts == nil {
		// Select some reasonable default options.
		switch img := img.(type) {
		case Image:
			o = EncodeOptions{
				Format:   img.Format(),
				MaxValue: img.MaxValue(),
			o = EncodeOptions{
				Format:   PPM,
				MaxValue: 255,
	} else {
		// Ensure the provided options are sensible.
		o = *opts
		if o.MaxValue < 0 {
			return errors.New("MaxValue must be greater than 0")
	switch o.Format {
	case PPM:
		return encodePPM(w, img, &o)
	case PGM:
		return encodePGM(w, img, &o)
	case PBM:
		return encodePBM(w, img, &o)
		return fmt.Errorf("Invalid Netpbm format specified (%s)", o.Format)