github.com/varialus/godfly@v0.0.0-20130904042352-1934f9f095ab/src/pkg/image/jpeg/writer.go (about)

     1  // Copyright 2011 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.
     4  
     5  package jpeg
     6  
     7  import (
     8  	"bufio"
     9  	"errors"
    10  	"image"
    11  	"image/color"
    12  	"io"
    13  )
    14  
    15  // min returns the minimum of two integers.
    16  func min(x, y int) int {
    17  	if x < y {
    18  		return x
    19  	}
    20  	return y
    21  }
    22  
    23  // div returns a/b rounded to the nearest integer, instead of rounded to zero.
    24  func div(a, b int32) int32 {
    25  	if a >= 0 {
    26  		return (a + (b >> 1)) / b
    27  	}
    28  	return -((-a + (b >> 1)) / b)
    29  }
    30  
    31  // bitCount counts the number of bits needed to hold an integer.
    32  var bitCount = [256]byte{
    33  	0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
    34  	5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
    35  	6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
    36  	6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
    37  	7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
    38  	7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
    39  	7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
    40  	7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
    41  	8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
    42  	8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
    43  	8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
    44  	8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
    45  	8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
    46  	8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
    47  	8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
    48  	8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
    49  }
    50  
    51  type quantIndex int
    52  
    53  const (
    54  	quantIndexLuminance quantIndex = iota
    55  	quantIndexChrominance
    56  	nQuantIndex
    57  )
    58  
    59  // unscaledQuant are the unscaled quantization tables in zig-zag order. Each
    60  // encoder copies and scales the tables according to its quality parameter.
    61  // The values are derived from section K.1 after converting from natural to
    62  // zig-zag order.
    63  var unscaledQuant = [nQuantIndex][blockSize]byte{
    64  	// Luminance.
    65  	{
    66  		16, 11, 12, 14, 12, 10, 16, 14,
    67  		13, 14, 18, 17, 16, 19, 24, 40,
    68  		26, 24, 22, 22, 24, 49, 35, 37,
    69  		29, 40, 58, 51, 61, 60, 57, 51,
    70  		56, 55, 64, 72, 92, 78, 64, 68,
    71  		87, 69, 55, 56, 80, 109, 81, 87,
    72  		95, 98, 103, 104, 103, 62, 77, 113,
    73  		121, 112, 100, 120, 92, 101, 103, 99,
    74  	},
    75  	// Chrominance.
    76  	{
    77  		17, 18, 18, 24, 21, 24, 47, 26,
    78  		26, 47, 99, 66, 56, 66, 99, 99,
    79  		99, 99, 99, 99, 99, 99, 99, 99,
    80  		99, 99, 99, 99, 99, 99, 99, 99,
    81  		99, 99, 99, 99, 99, 99, 99, 99,
    82  		99, 99, 99, 99, 99, 99, 99, 99,
    83  		99, 99, 99, 99, 99, 99, 99, 99,
    84  		99, 99, 99, 99, 99, 99, 99, 99,
    85  	},
    86  }
    87  
    88  type huffIndex int
    89  
    90  const (
    91  	huffIndexLuminanceDC huffIndex = iota
    92  	huffIndexLuminanceAC
    93  	huffIndexChrominanceDC
    94  	huffIndexChrominanceAC
    95  	nHuffIndex
    96  )
    97  
    98  // huffmanSpec specifies a Huffman encoding.
    99  type huffmanSpec struct {
   100  	// count[i] is the number of codes of length i bits.
   101  	count [16]byte
   102  	// value[i] is the decoded value of the i'th codeword.
   103  	value []byte
   104  }
   105  
   106  // theHuffmanSpec is the Huffman encoding specifications.
   107  // This encoder uses the same Huffman encoding for all images.
   108  var theHuffmanSpec = [nHuffIndex]huffmanSpec{
   109  	// Luminance DC.
   110  	{
   111  		[16]byte{0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0},
   112  		[]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11},
   113  	},
   114  	// Luminance AC.
   115  	{
   116  		[16]byte{0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 125},
   117  		[]byte{
   118  			0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
   119  			0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
   120  			0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
   121  			0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
   122  			0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
   123  			0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
   124  			0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
   125  			0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
   126  			0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
   127  			0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
   128  			0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
   129  			0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
   130  			0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
   131  			0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
   132  			0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
   133  			0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
   134  			0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
   135  			0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
   136  			0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
   137  			0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
   138  			0xf9, 0xfa,
   139  		},
   140  	},
   141  	// Chrominance DC.
   142  	{
   143  		[16]byte{0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0},
   144  		[]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11},
   145  	},
   146  	// Chrominance AC.
   147  	{
   148  		[16]byte{0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 119},
   149  		[]byte{
   150  			0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
   151  			0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
   152  			0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
   153  			0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
   154  			0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
   155  			0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
   156  			0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
   157  			0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
   158  			0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
   159  			0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
   160  			0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
   161  			0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
   162  			0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
   163  			0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
   164  			0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
   165  			0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
   166  			0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
   167  			0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
   168  			0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
   169  			0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
   170  			0xf9, 0xfa,
   171  		},
   172  	},
   173  }
   174  
   175  // huffmanLUT is a compiled look-up table representation of a huffmanSpec.
   176  // Each value maps to a uint32 of which the 8 most significant bits hold the
   177  // codeword size in bits and the 24 least significant bits hold the codeword.
   178  // The maximum codeword size is 16 bits.
   179  type huffmanLUT []uint32
   180  
   181  func (h *huffmanLUT) init(s huffmanSpec) {
   182  	maxValue := 0
   183  	for _, v := range s.value {
   184  		if int(v) > maxValue {
   185  			maxValue = int(v)
   186  		}
   187  	}
   188  	*h = make([]uint32, maxValue+1)
   189  	code, k := uint32(0), 0
   190  	for i := 0; i < len(s.count); i++ {
   191  		nBits := uint32(i+1) << 24
   192  		for j := uint8(0); j < s.count[i]; j++ {
   193  			(*h)[s.value[k]] = nBits | code
   194  			code++
   195  			k++
   196  		}
   197  		code <<= 1
   198  	}
   199  }
   200  
   201  // theHuffmanLUT are compiled representations of theHuffmanSpec.
   202  var theHuffmanLUT [4]huffmanLUT
   203  
   204  func init() {
   205  	for i, s := range theHuffmanSpec {
   206  		theHuffmanLUT[i].init(s)
   207  	}
   208  }
   209  
   210  // writer is a buffered writer.
   211  type writer interface {
   212  	Flush() error
   213  	io.Writer
   214  	io.ByteWriter
   215  }
   216  
   217  // encoder encodes an image to the JPEG format.
   218  type encoder struct {
   219  	// w is the writer to write to. err is the first error encountered during
   220  	// writing. All attempted writes after the first error become no-ops.
   221  	w   writer
   222  	err error
   223  	// buf is a scratch buffer.
   224  	buf [16]byte
   225  	// bits and nBits are accumulated bits to write to w.
   226  	bits, nBits uint32
   227  	// quant is the scaled quantization tables, in zig-zag order.
   228  	quant [nQuantIndex][blockSize]byte
   229  }
   230  
   231  func (e *encoder) flush() {
   232  	if e.err != nil {
   233  		return
   234  	}
   235  	e.err = e.w.Flush()
   236  }
   237  
   238  func (e *encoder) write(p []byte) {
   239  	if e.err != nil {
   240  		return
   241  	}
   242  	_, e.err = e.w.Write(p)
   243  }
   244  
   245  func (e *encoder) writeByte(b byte) {
   246  	if e.err != nil {
   247  		return
   248  	}
   249  	e.err = e.w.WriteByte(b)
   250  }
   251  
   252  // emit emits the least significant nBits bits of bits to the bitstream.
   253  // The precondition is bits < 1<<nBits && nBits <= 16.
   254  func (e *encoder) emit(bits, nBits uint32) {
   255  	nBits += e.nBits
   256  	bits <<= 32 - nBits
   257  	bits |= e.bits
   258  	for nBits >= 8 {
   259  		b := uint8(bits >> 24)
   260  		e.writeByte(b)
   261  		if b == 0xff {
   262  			e.writeByte(0x00)
   263  		}
   264  		bits <<= 8
   265  		nBits -= 8
   266  	}
   267  	e.bits, e.nBits = bits, nBits
   268  }
   269  
   270  // emitHuff emits the given value with the given Huffman encoder.
   271  func (e *encoder) emitHuff(h huffIndex, value int32) {
   272  	x := theHuffmanLUT[h][value]
   273  	e.emit(x&(1<<24-1), x>>24)
   274  }
   275  
   276  // emitHuffRLE emits a run of runLength copies of value encoded with the given
   277  // Huffman encoder.
   278  func (e *encoder) emitHuffRLE(h huffIndex, runLength, value int32) {
   279  	a, b := value, value
   280  	if a < 0 {
   281  		a, b = -value, value-1
   282  	}
   283  	var nBits uint32
   284  	if a < 0x100 {
   285  		nBits = uint32(bitCount[a])
   286  	} else {
   287  		nBits = 8 + uint32(bitCount[a>>8])
   288  	}
   289  	e.emitHuff(h, runLength<<4|int32(nBits))
   290  	if nBits > 0 {
   291  		e.emit(uint32(b)&(1<<nBits-1), nBits)
   292  	}
   293  }
   294  
   295  // writeMarkerHeader writes the header for a marker with the given length.
   296  func (e *encoder) writeMarkerHeader(marker uint8, markerlen int) {
   297  	e.buf[0] = 0xff
   298  	e.buf[1] = marker
   299  	e.buf[2] = uint8(markerlen >> 8)
   300  	e.buf[3] = uint8(markerlen & 0xff)
   301  	e.write(e.buf[:4])
   302  }
   303  
   304  // writeDQT writes the Define Quantization Table marker.
   305  func (e *encoder) writeDQT() {
   306  	const markerlen = 2 + int(nQuantIndex)*(1+blockSize)
   307  	e.writeMarkerHeader(dqtMarker, markerlen)
   308  	for i := range e.quant {
   309  		e.writeByte(uint8(i))
   310  		e.write(e.quant[i][:])
   311  	}
   312  }
   313  
   314  // writeSOF0 writes the Start Of Frame (Baseline) marker.
   315  func (e *encoder) writeSOF0(size image.Point) {
   316  	const markerlen = 8 + 3*nColorComponent
   317  	e.writeMarkerHeader(sof0Marker, markerlen)
   318  	e.buf[0] = 8 // 8-bit color.
   319  	e.buf[1] = uint8(size.Y >> 8)
   320  	e.buf[2] = uint8(size.Y & 0xff)
   321  	e.buf[3] = uint8(size.X >> 8)
   322  	e.buf[4] = uint8(size.X & 0xff)
   323  	e.buf[5] = nColorComponent
   324  	for i := 0; i < nColorComponent; i++ {
   325  		e.buf[3*i+6] = uint8(i + 1)
   326  		// We use 4:2:0 chroma subsampling.
   327  		e.buf[3*i+7] = "\x22\x11\x11"[i]
   328  		e.buf[3*i+8] = "\x00\x01\x01"[i]
   329  	}
   330  	e.write(e.buf[:3*(nColorComponent-1)+9])
   331  }
   332  
   333  // writeDHT writes the Define Huffman Table marker.
   334  func (e *encoder) writeDHT() {
   335  	markerlen := 2
   336  	for _, s := range theHuffmanSpec {
   337  		markerlen += 1 + 16 + len(s.value)
   338  	}
   339  	e.writeMarkerHeader(dhtMarker, markerlen)
   340  	for i, s := range theHuffmanSpec {
   341  		e.writeByte("\x00\x10\x01\x11"[i])
   342  		e.write(s.count[:])
   343  		e.write(s.value)
   344  	}
   345  }
   346  
   347  // writeBlock writes a block of pixel data using the given quantization table,
   348  // returning the post-quantized DC value of the DCT-transformed block.
   349  // b is in natural (not zig-zag) order.
   350  func (e *encoder) writeBlock(b *block, q quantIndex, prevDC int32) int32 {
   351  	fdct(b)
   352  	// Emit the DC delta.
   353  	dc := div(b[0], 8*int32(e.quant[q][0]))
   354  	e.emitHuffRLE(huffIndex(2*q+0), 0, dc-prevDC)
   355  	// Emit the AC components.
   356  	h, runLength := huffIndex(2*q+1), int32(0)
   357  	for zig := 1; zig < blockSize; zig++ {
   358  		ac := div(b[unzig[zig]], 8*int32(e.quant[q][zig]))
   359  		if ac == 0 {
   360  			runLength++
   361  		} else {
   362  			for runLength > 15 {
   363  				e.emitHuff(h, 0xf0)
   364  				runLength -= 16
   365  			}
   366  			e.emitHuffRLE(h, runLength, ac)
   367  			runLength = 0
   368  		}
   369  	}
   370  	if runLength > 0 {
   371  		e.emitHuff(h, 0x00)
   372  	}
   373  	return dc
   374  }
   375  
   376  // toYCbCr converts the 8x8 region of m whose top-left corner is p to its
   377  // YCbCr values.
   378  func toYCbCr(m image.Image, p image.Point, yBlock, cbBlock, crBlock *block) {
   379  	b := m.Bounds()
   380  	xmax := b.Max.X - 1
   381  	ymax := b.Max.Y - 1
   382  	for j := 0; j < 8; j++ {
   383  		for i := 0; i < 8; i++ {
   384  			r, g, b, _ := m.At(min(p.X+i, xmax), min(p.Y+j, ymax)).RGBA()
   385  			yy, cb, cr := color.RGBToYCbCr(uint8(r>>8), uint8(g>>8), uint8(b>>8))
   386  			yBlock[8*j+i] = int32(yy)
   387  			cbBlock[8*j+i] = int32(cb)
   388  			crBlock[8*j+i] = int32(cr)
   389  		}
   390  	}
   391  }
   392  
   393  // rgbaToYCbCr is a specialized version of toYCbCr for image.RGBA images.
   394  func rgbaToYCbCr(m *image.RGBA, p image.Point, yBlock, cbBlock, crBlock *block) {
   395  	b := m.Bounds()
   396  	xmax := b.Max.X - 1
   397  	ymax := b.Max.Y - 1
   398  	for j := 0; j < 8; j++ {
   399  		sj := p.Y + j
   400  		if sj > ymax {
   401  			sj = ymax
   402  		}
   403  		offset := (sj-b.Min.Y)*m.Stride - b.Min.X*4
   404  		for i := 0; i < 8; i++ {
   405  			sx := p.X + i
   406  			if sx > xmax {
   407  				sx = xmax
   408  			}
   409  			pix := m.Pix[offset+sx*4:]
   410  			yy, cb, cr := color.RGBToYCbCr(pix[0], pix[1], pix[2])
   411  			yBlock[8*j+i] = int32(yy)
   412  			cbBlock[8*j+i] = int32(cb)
   413  			crBlock[8*j+i] = int32(cr)
   414  		}
   415  	}
   416  }
   417  
   418  // scale scales the 16x16 region represented by the 4 src blocks to the 8x8
   419  // dst block.
   420  func scale(dst *block, src *[4]block) {
   421  	for i := 0; i < 4; i++ {
   422  		dstOff := (i&2)<<4 | (i&1)<<2
   423  		for y := 0; y < 4; y++ {
   424  			for x := 0; x < 4; x++ {
   425  				j := 16*y + 2*x
   426  				sum := src[i][j] + src[i][j+1] + src[i][j+8] + src[i][j+9]
   427  				dst[8*y+x+dstOff] = (sum + 2) >> 2
   428  			}
   429  		}
   430  	}
   431  }
   432  
   433  // sosHeader is the SOS marker "\xff\xda" followed by 12 bytes:
   434  //	- the marker length "\x00\x0c",
   435  //	- the number of components "\x03",
   436  //	- component 1 uses DC table 0 and AC table 0 "\x01\x00",
   437  //	- component 2 uses DC table 1 and AC table 1 "\x02\x11",
   438  //	- component 3 uses DC table 1 and AC table 1 "\x03\x11",
   439  //	- the bytes "\x00\x3f\x00". Section B.2.3 of the spec says that for
   440  //	  sequential DCTs, those bytes (8-bit Ss, 8-bit Se, 4-bit Ah, 4-bit Al)
   441  //	  should be 0x00, 0x3f, 0x00<<4 | 0x00.
   442  var sosHeader = []byte{
   443  	0xff, 0xda, 0x00, 0x0c, 0x03, 0x01, 0x00, 0x02,
   444  	0x11, 0x03, 0x11, 0x00, 0x3f, 0x00,
   445  }
   446  
   447  // writeSOS writes the StartOfScan marker.
   448  func (e *encoder) writeSOS(m image.Image) {
   449  	e.write(sosHeader)
   450  	var (
   451  		// Scratch buffers to hold the YCbCr values.
   452  		// The blocks are in natural (not zig-zag) order.
   453  		b      block
   454  		cb, cr [4]block
   455  		// DC components are delta-encoded.
   456  		prevDCY, prevDCCb, prevDCCr int32
   457  	)
   458  	bounds := m.Bounds()
   459  	rgba, _ := m.(*image.RGBA)
   460  	for y := bounds.Min.Y; y < bounds.Max.Y; y += 16 {
   461  		for x := bounds.Min.X; x < bounds.Max.X; x += 16 {
   462  			for i := 0; i < 4; i++ {
   463  				xOff := (i & 1) * 8
   464  				yOff := (i & 2) * 4
   465  				p := image.Pt(x+xOff, y+yOff)
   466  				if rgba != nil {
   467  					rgbaToYCbCr(rgba, p, &b, &cb[i], &cr[i])
   468  				} else {
   469  					toYCbCr(m, p, &b, &cb[i], &cr[i])
   470  				}
   471  				prevDCY = e.writeBlock(&b, 0, prevDCY)
   472  			}
   473  			scale(&b, &cb)
   474  			prevDCCb = e.writeBlock(&b, 1, prevDCCb)
   475  			scale(&b, &cr)
   476  			prevDCCr = e.writeBlock(&b, 1, prevDCCr)
   477  		}
   478  	}
   479  	// Pad the last byte with 1's.
   480  	e.emit(0x7f, 7)
   481  }
   482  
   483  // DefaultQuality is the default quality encoding parameter.
   484  const DefaultQuality = 75
   485  
   486  // Options are the encoding parameters.
   487  // Quality ranges from 1 to 100 inclusive, higher is better.
   488  type Options struct {
   489  	Quality int
   490  }
   491  
   492  // Encode writes the Image m to w in JPEG 4:2:0 baseline format with the given
   493  // options. Default parameters are used if a nil *Options is passed.
   494  func Encode(w io.Writer, m image.Image, o *Options) error {
   495  	b := m.Bounds()
   496  	if b.Dx() >= 1<<16 || b.Dy() >= 1<<16 {
   497  		return errors.New("jpeg: image is too large to encode")
   498  	}
   499  	var e encoder
   500  	if ww, ok := w.(writer); ok {
   501  		e.w = ww
   502  	} else {
   503  		e.w = bufio.NewWriter(w)
   504  	}
   505  	// Clip quality to [1, 100].
   506  	quality := DefaultQuality
   507  	if o != nil {
   508  		quality = o.Quality
   509  		if quality < 1 {
   510  			quality = 1
   511  		} else if quality > 100 {
   512  			quality = 100
   513  		}
   514  	}
   515  	// Convert from a quality rating to a scaling factor.
   516  	var scale int
   517  	if quality < 50 {
   518  		scale = 5000 / quality
   519  	} else {
   520  		scale = 200 - quality*2
   521  	}
   522  	// Initialize the quantization tables.
   523  	for i := range e.quant {
   524  		for j := range e.quant[i] {
   525  			x := int(unscaledQuant[i][j])
   526  			x = (x*scale + 50) / 100
   527  			if x < 1 {
   528  				x = 1
   529  			} else if x > 255 {
   530  				x = 255
   531  			}
   532  			e.quant[i][j] = uint8(x)
   533  		}
   534  	}
   535  	// Write the Start Of Image marker.
   536  	e.buf[0] = 0xff
   537  	e.buf[1] = 0xd8
   538  	e.write(e.buf[:2])
   539  	// Write the quantization tables.
   540  	e.writeDQT()
   541  	// Write the image dimensions.
   542  	e.writeSOF0(b.Size())
   543  	// Write the Huffman tables.
   544  	e.writeDHT()
   545  	// Write the image data.
   546  	e.writeSOS(m)
   547  	// Write the End Of Image marker.
   548  	e.buf[0] = 0xff
   549  	e.buf[1] = 0xd9
   550  	e.write(e.buf[:2])
   551  	e.flush()
   552  	return e.err
   553  }