github.com/rsc/go@v0.0.0-20150416155037-e040fd465409/src/image/draw/draw.go (about)

     1  // Copyright 2009 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 draw provides image composition functions.
     6  //
     7  // See "The Go image/draw package" for an introduction to this package:
     8  // http://golang.org/doc/articles/image_draw.html
     9  package draw
    10  
    11  import (
    12  	"image"
    13  	"image/color"
    14  	"image/internal/imageutil"
    15  )
    16  
    17  // m is the maximum color value returned by image.Color.RGBA.
    18  const m = 1<<16 - 1
    19  
    20  // Image is an image.Image with a Set method to change a single pixel.
    21  type Image interface {
    22  	image.Image
    23  	Set(x, y int, c color.Color)
    24  }
    25  
    26  // Quantizer produces a palette for an image.
    27  type Quantizer interface {
    28  	// Quantize appends up to cap(p) - len(p) colors to p and returns the
    29  	// updated palette suitable for converting m to a paletted image.
    30  	Quantize(p color.Palette, m image.Image) color.Palette
    31  }
    32  
    33  // Op is a Porter-Duff compositing operator.
    34  type Op int
    35  
    36  const (
    37  	// Over specifies ``(src in mask) over dst''.
    38  	Over Op = iota
    39  	// Src specifies ``src in mask''.
    40  	Src
    41  )
    42  
    43  // Draw implements the Drawer interface by calling the Draw function with this
    44  // Op.
    45  func (op Op) Draw(dst Image, r image.Rectangle, src image.Image, sp image.Point) {
    46  	DrawMask(dst, r, src, sp, nil, image.Point{}, op)
    47  }
    48  
    49  // Drawer contains the Draw method.
    50  type Drawer interface {
    51  	// Draw aligns r.Min in dst with sp in src and then replaces the
    52  	// rectangle r in dst with the result of drawing src on dst.
    53  	Draw(dst Image, r image.Rectangle, src image.Image, sp image.Point)
    54  }
    55  
    56  // FloydSteinberg is a Drawer that is the Src Op with Floyd-Steinberg error
    57  // diffusion.
    58  var FloydSteinberg Drawer = floydSteinberg{}
    59  
    60  type floydSteinberg struct{}
    61  
    62  func (floydSteinberg) Draw(dst Image, r image.Rectangle, src image.Image, sp image.Point) {
    63  	clip(dst, &r, src, &sp, nil, nil)
    64  	if r.Empty() {
    65  		return
    66  	}
    67  	drawPaletted(dst, r, src, sp, true)
    68  }
    69  
    70  // clip clips r against each image's bounds (after translating into the
    71  // destination image's coordinate space) and shifts the points sp and mp by
    72  // the same amount as the change in r.Min.
    73  func clip(dst Image, r *image.Rectangle, src image.Image, sp *image.Point, mask image.Image, mp *image.Point) {
    74  	orig := r.Min
    75  	*r = r.Intersect(dst.Bounds())
    76  	*r = r.Intersect(src.Bounds().Add(orig.Sub(*sp)))
    77  	if mask != nil {
    78  		*r = r.Intersect(mask.Bounds().Add(orig.Sub(*mp)))
    79  	}
    80  	dx := r.Min.X - orig.X
    81  	dy := r.Min.Y - orig.Y
    82  	if dx == 0 && dy == 0 {
    83  		return
    84  	}
    85  	sp.X += dx
    86  	sp.Y += dy
    87  	if mp != nil {
    88  		mp.X += dx
    89  		mp.Y += dy
    90  	}
    91  }
    92  
    93  func processBackward(dst Image, r image.Rectangle, src image.Image, sp image.Point) bool {
    94  	return image.Image(dst) == src &&
    95  		r.Overlaps(r.Add(sp.Sub(r.Min))) &&
    96  		(sp.Y < r.Min.Y || (sp.Y == r.Min.Y && sp.X < r.Min.X))
    97  }
    98  
    99  // Draw calls DrawMask with a nil mask.
   100  func Draw(dst Image, r image.Rectangle, src image.Image, sp image.Point, op Op) {
   101  	DrawMask(dst, r, src, sp, nil, image.Point{}, op)
   102  }
   103  
   104  // DrawMask aligns r.Min in dst with sp in src and mp in mask and then replaces the rectangle r
   105  // in dst with the result of a Porter-Duff composition. A nil mask is treated as opaque.
   106  func DrawMask(dst Image, r image.Rectangle, src image.Image, sp image.Point, mask image.Image, mp image.Point, op Op) {
   107  	clip(dst, &r, src, &sp, mask, &mp)
   108  	if r.Empty() {
   109  		return
   110  	}
   111  
   112  	// Fast paths for special cases. If none of them apply, then we fall back to a general but slow implementation.
   113  	switch dst0 := dst.(type) {
   114  	case *image.RGBA:
   115  		if op == Over {
   116  			if mask == nil {
   117  				switch src0 := src.(type) {
   118  				case *image.Uniform:
   119  					drawFillOver(dst0, r, src0)
   120  					return
   121  				case *image.RGBA:
   122  					drawCopyOver(dst0, r, src0, sp)
   123  					return
   124  				case *image.NRGBA:
   125  					drawNRGBAOver(dst0, r, src0, sp)
   126  					return
   127  				case *image.YCbCr:
   128  					// An image.YCbCr is always fully opaque, and so if the
   129  					// mask is nil (i.e. fully opaque) then the op is
   130  					// effectively always Src. Similarly for image.Gray and
   131  					// image.CMYK.
   132  					if imageutil.DrawYCbCr(dst0, r, src0, sp) {
   133  						return
   134  					}
   135  				case *image.Gray:
   136  					drawGray(dst0, r, src0, sp)
   137  					return
   138  				case *image.CMYK:
   139  					drawCMYK(dst0, r, src0, sp)
   140  					return
   141  				}
   142  			} else if mask0, ok := mask.(*image.Alpha); ok {
   143  				switch src0 := src.(type) {
   144  				case *image.Uniform:
   145  					drawGlyphOver(dst0, r, src0, mask0, mp)
   146  					return
   147  				}
   148  			}
   149  		} else {
   150  			if mask == nil {
   151  				switch src0 := src.(type) {
   152  				case *image.Uniform:
   153  					drawFillSrc(dst0, r, src0)
   154  					return
   155  				case *image.RGBA:
   156  					drawCopySrc(dst0, r, src0, sp)
   157  					return
   158  				case *image.NRGBA:
   159  					drawNRGBASrc(dst0, r, src0, sp)
   160  					return
   161  				case *image.YCbCr:
   162  					if imageutil.DrawYCbCr(dst0, r, src0, sp) {
   163  						return
   164  					}
   165  				case *image.Gray:
   166  					drawGray(dst0, r, src0, sp)
   167  					return
   168  				case *image.CMYK:
   169  					drawCMYK(dst0, r, src0, sp)
   170  					return
   171  				}
   172  			}
   173  		}
   174  		drawRGBA(dst0, r, src, sp, mask, mp, op)
   175  		return
   176  	case *image.Paletted:
   177  		if op == Src && mask == nil && !processBackward(dst, r, src, sp) {
   178  			drawPaletted(dst0, r, src, sp, false)
   179  		}
   180  	}
   181  
   182  	x0, x1, dx := r.Min.X, r.Max.X, 1
   183  	y0, y1, dy := r.Min.Y, r.Max.Y, 1
   184  	if processBackward(dst, r, src, sp) {
   185  		x0, x1, dx = x1-1, x0-1, -1
   186  		y0, y1, dy = y1-1, y0-1, -1
   187  	}
   188  
   189  	var out color.RGBA64
   190  	sy := sp.Y + y0 - r.Min.Y
   191  	my := mp.Y + y0 - r.Min.Y
   192  	for y := y0; y != y1; y, sy, my = y+dy, sy+dy, my+dy {
   193  		sx := sp.X + x0 - r.Min.X
   194  		mx := mp.X + x0 - r.Min.X
   195  		for x := x0; x != x1; x, sx, mx = x+dx, sx+dx, mx+dx {
   196  			ma := uint32(m)
   197  			if mask != nil {
   198  				_, _, _, ma = mask.At(mx, my).RGBA()
   199  			}
   200  			switch {
   201  			case ma == 0:
   202  				if op == Over {
   203  					// No-op.
   204  				} else {
   205  					dst.Set(x, y, color.Transparent)
   206  				}
   207  			case ma == m && op == Src:
   208  				dst.Set(x, y, src.At(sx, sy))
   209  			default:
   210  				sr, sg, sb, sa := src.At(sx, sy).RGBA()
   211  				if op == Over {
   212  					dr, dg, db, da := dst.At(x, y).RGBA()
   213  					a := m - (sa * ma / m)
   214  					out.R = uint16((dr*a + sr*ma) / m)
   215  					out.G = uint16((dg*a + sg*ma) / m)
   216  					out.B = uint16((db*a + sb*ma) / m)
   217  					out.A = uint16((da*a + sa*ma) / m)
   218  				} else {
   219  					out.R = uint16(sr * ma / m)
   220  					out.G = uint16(sg * ma / m)
   221  					out.B = uint16(sb * ma / m)
   222  					out.A = uint16(sa * ma / m)
   223  				}
   224  				// The third argument is &out instead of out (and out is
   225  				// declared outside of the inner loop) to avoid the implicit
   226  				// conversion to color.Color here allocating memory in the
   227  				// inner loop if sizeof(color.RGBA64) > sizeof(uintptr).
   228  				dst.Set(x, y, &out)
   229  			}
   230  		}
   231  	}
   232  }
   233  
   234  func drawFillOver(dst *image.RGBA, r image.Rectangle, src *image.Uniform) {
   235  	sr, sg, sb, sa := src.RGBA()
   236  	// The 0x101 is here for the same reason as in drawRGBA.
   237  	a := (m - sa) * 0x101
   238  	i0 := dst.PixOffset(r.Min.X, r.Min.Y)
   239  	i1 := i0 + r.Dx()*4
   240  	for y := r.Min.Y; y != r.Max.Y; y++ {
   241  		for i := i0; i < i1; i += 4 {
   242  			dr := uint32(dst.Pix[i+0])
   243  			dg := uint32(dst.Pix[i+1])
   244  			db := uint32(dst.Pix[i+2])
   245  			da := uint32(dst.Pix[i+3])
   246  
   247  			dst.Pix[i+0] = uint8((dr*a/m + sr) >> 8)
   248  			dst.Pix[i+1] = uint8((dg*a/m + sg) >> 8)
   249  			dst.Pix[i+2] = uint8((db*a/m + sb) >> 8)
   250  			dst.Pix[i+3] = uint8((da*a/m + sa) >> 8)
   251  		}
   252  		i0 += dst.Stride
   253  		i1 += dst.Stride
   254  	}
   255  }
   256  
   257  func drawFillSrc(dst *image.RGBA, r image.Rectangle, src *image.Uniform) {
   258  	sr, sg, sb, sa := src.RGBA()
   259  	sr8 := uint8(sr >> 8)
   260  	sg8 := uint8(sg >> 8)
   261  	sb8 := uint8(sb >> 8)
   262  	sa8 := uint8(sa >> 8)
   263  	// The built-in copy function is faster than a straightforward for loop to fill the destination with
   264  	// the color, but copy requires a slice source. We therefore use a for loop to fill the first row, and
   265  	// then use the first row as the slice source for the remaining rows.
   266  	i0 := dst.PixOffset(r.Min.X, r.Min.Y)
   267  	i1 := i0 + r.Dx()*4
   268  	for i := i0; i < i1; i += 4 {
   269  		dst.Pix[i+0] = sr8
   270  		dst.Pix[i+1] = sg8
   271  		dst.Pix[i+2] = sb8
   272  		dst.Pix[i+3] = sa8
   273  	}
   274  	firstRow := dst.Pix[i0:i1]
   275  	for y := r.Min.Y + 1; y < r.Max.Y; y++ {
   276  		i0 += dst.Stride
   277  		i1 += dst.Stride
   278  		copy(dst.Pix[i0:i1], firstRow)
   279  	}
   280  }
   281  
   282  func drawCopyOver(dst *image.RGBA, r image.Rectangle, src *image.RGBA, sp image.Point) {
   283  	dx, dy := r.Dx(), r.Dy()
   284  	d0 := dst.PixOffset(r.Min.X, r.Min.Y)
   285  	s0 := src.PixOffset(sp.X, sp.Y)
   286  	var (
   287  		ddelta, sdelta int
   288  		i0, i1, idelta int
   289  	)
   290  	if r.Min.Y < sp.Y || r.Min.Y == sp.Y && r.Min.X <= sp.X {
   291  		ddelta = dst.Stride
   292  		sdelta = src.Stride
   293  		i0, i1, idelta = 0, dx*4, +4
   294  	} else {
   295  		// If the source start point is higher than the destination start point, or equal height but to the left,
   296  		// then we compose the rows in right-to-left, bottom-up order instead of left-to-right, top-down.
   297  		d0 += (dy - 1) * dst.Stride
   298  		s0 += (dy - 1) * src.Stride
   299  		ddelta = -dst.Stride
   300  		sdelta = -src.Stride
   301  		i0, i1, idelta = (dx-1)*4, -4, -4
   302  	}
   303  	for ; dy > 0; dy-- {
   304  		dpix := dst.Pix[d0:]
   305  		spix := src.Pix[s0:]
   306  		for i := i0; i != i1; i += idelta {
   307  			sr := uint32(spix[i+0]) * 0x101
   308  			sg := uint32(spix[i+1]) * 0x101
   309  			sb := uint32(spix[i+2]) * 0x101
   310  			sa := uint32(spix[i+3]) * 0x101
   311  
   312  			dr := uint32(dpix[i+0])
   313  			dg := uint32(dpix[i+1])
   314  			db := uint32(dpix[i+2])
   315  			da := uint32(dpix[i+3])
   316  
   317  			// The 0x101 is here for the same reason as in drawRGBA.
   318  			a := (m - sa) * 0x101
   319  
   320  			dpix[i+0] = uint8((dr*a/m + sr) >> 8)
   321  			dpix[i+1] = uint8((dg*a/m + sg) >> 8)
   322  			dpix[i+2] = uint8((db*a/m + sb) >> 8)
   323  			dpix[i+3] = uint8((da*a/m + sa) >> 8)
   324  		}
   325  		d0 += ddelta
   326  		s0 += sdelta
   327  	}
   328  }
   329  
   330  func drawCopySrc(dst *image.RGBA, r image.Rectangle, src *image.RGBA, sp image.Point) {
   331  	n, dy := 4*r.Dx(), r.Dy()
   332  	d0 := dst.PixOffset(r.Min.X, r.Min.Y)
   333  	s0 := src.PixOffset(sp.X, sp.Y)
   334  	var ddelta, sdelta int
   335  	if r.Min.Y <= sp.Y {
   336  		ddelta = dst.Stride
   337  		sdelta = src.Stride
   338  	} else {
   339  		// If the source start point is higher than the destination start
   340  		// point, then we compose the rows in bottom-up order instead of
   341  		// top-down. Unlike the drawCopyOver function, we don't have to check
   342  		// the x coordinates because the built-in copy function can handle
   343  		// overlapping slices.
   344  		d0 += (dy - 1) * dst.Stride
   345  		s0 += (dy - 1) * src.Stride
   346  		ddelta = -dst.Stride
   347  		sdelta = -src.Stride
   348  	}
   349  	for ; dy > 0; dy-- {
   350  		copy(dst.Pix[d0:d0+n], src.Pix[s0:s0+n])
   351  		d0 += ddelta
   352  		s0 += sdelta
   353  	}
   354  }
   355  
   356  func drawNRGBAOver(dst *image.RGBA, r image.Rectangle, src *image.NRGBA, sp image.Point) {
   357  	i0 := (r.Min.X - dst.Rect.Min.X) * 4
   358  	i1 := (r.Max.X - dst.Rect.Min.X) * 4
   359  	si0 := (sp.X - src.Rect.Min.X) * 4
   360  	yMax := r.Max.Y - dst.Rect.Min.Y
   361  
   362  	y := r.Min.Y - dst.Rect.Min.Y
   363  	sy := sp.Y - src.Rect.Min.Y
   364  	for ; y != yMax; y, sy = y+1, sy+1 {
   365  		dpix := dst.Pix[y*dst.Stride:]
   366  		spix := src.Pix[sy*src.Stride:]
   367  
   368  		for i, si := i0, si0; i < i1; i, si = i+4, si+4 {
   369  			// Convert from non-premultiplied color to pre-multiplied color.
   370  			sa := uint32(spix[si+3]) * 0x101
   371  			sr := uint32(spix[si+0]) * sa / 0xff
   372  			sg := uint32(spix[si+1]) * sa / 0xff
   373  			sb := uint32(spix[si+2]) * sa / 0xff
   374  
   375  			dr := uint32(dpix[i+0])
   376  			dg := uint32(dpix[i+1])
   377  			db := uint32(dpix[i+2])
   378  			da := uint32(dpix[i+3])
   379  
   380  			// The 0x101 is here for the same reason as in drawRGBA.
   381  			a := (m - sa) * 0x101
   382  
   383  			dpix[i+0] = uint8((dr*a/m + sr) >> 8)
   384  			dpix[i+1] = uint8((dg*a/m + sg) >> 8)
   385  			dpix[i+2] = uint8((db*a/m + sb) >> 8)
   386  			dpix[i+3] = uint8((da*a/m + sa) >> 8)
   387  		}
   388  	}
   389  }
   390  
   391  func drawNRGBASrc(dst *image.RGBA, r image.Rectangle, src *image.NRGBA, sp image.Point) {
   392  	i0 := (r.Min.X - dst.Rect.Min.X) * 4
   393  	i1 := (r.Max.X - dst.Rect.Min.X) * 4
   394  	si0 := (sp.X - src.Rect.Min.X) * 4
   395  	yMax := r.Max.Y - dst.Rect.Min.Y
   396  
   397  	y := r.Min.Y - dst.Rect.Min.Y
   398  	sy := sp.Y - src.Rect.Min.Y
   399  	for ; y != yMax; y, sy = y+1, sy+1 {
   400  		dpix := dst.Pix[y*dst.Stride:]
   401  		spix := src.Pix[sy*src.Stride:]
   402  
   403  		for i, si := i0, si0; i < i1; i, si = i+4, si+4 {
   404  			// Convert from non-premultiplied color to pre-multiplied color.
   405  			sa := uint32(spix[si+3]) * 0x101
   406  			sr := uint32(spix[si+0]) * sa / 0xff
   407  			sg := uint32(spix[si+1]) * sa / 0xff
   408  			sb := uint32(spix[si+2]) * sa / 0xff
   409  
   410  			dpix[i+0] = uint8(sr >> 8)
   411  			dpix[i+1] = uint8(sg >> 8)
   412  			dpix[i+2] = uint8(sb >> 8)
   413  			dpix[i+3] = uint8(sa >> 8)
   414  		}
   415  	}
   416  }
   417  
   418  func drawGray(dst *image.RGBA, r image.Rectangle, src *image.Gray, sp image.Point) {
   419  	i0 := (r.Min.X - dst.Rect.Min.X) * 4
   420  	i1 := (r.Max.X - dst.Rect.Min.X) * 4
   421  	si0 := (sp.X - src.Rect.Min.X) * 1
   422  	yMax := r.Max.Y - dst.Rect.Min.Y
   423  
   424  	y := r.Min.Y - dst.Rect.Min.Y
   425  	sy := sp.Y - src.Rect.Min.Y
   426  	for ; y != yMax; y, sy = y+1, sy+1 {
   427  		dpix := dst.Pix[y*dst.Stride:]
   428  		spix := src.Pix[sy*src.Stride:]
   429  
   430  		for i, si := i0, si0; i < i1; i, si = i+4, si+1 {
   431  			p := spix[si]
   432  			dpix[i+0] = p
   433  			dpix[i+1] = p
   434  			dpix[i+2] = p
   435  			dpix[i+3] = 255
   436  		}
   437  	}
   438  }
   439  
   440  func drawCMYK(dst *image.RGBA, r image.Rectangle, src *image.CMYK, sp image.Point) {
   441  	i0 := (r.Min.X - dst.Rect.Min.X) * 4
   442  	i1 := (r.Max.X - dst.Rect.Min.X) * 4
   443  	si0 := (sp.X - src.Rect.Min.X) * 4
   444  	yMax := r.Max.Y - dst.Rect.Min.Y
   445  
   446  	y := r.Min.Y - dst.Rect.Min.Y
   447  	sy := sp.Y - src.Rect.Min.Y
   448  	for ; y != yMax; y, sy = y+1, sy+1 {
   449  		dpix := dst.Pix[y*dst.Stride:]
   450  		spix := src.Pix[sy*src.Stride:]
   451  
   452  		for i, si := i0, si0; i < i1; i, si = i+4, si+4 {
   453  			dpix[i+0], dpix[i+1], dpix[i+2] =
   454  				color.CMYKToRGB(spix[si+0], spix[si+1], spix[si+2], spix[si+3])
   455  			dpix[i+3] = 255
   456  		}
   457  	}
   458  }
   459  
   460  func drawGlyphOver(dst *image.RGBA, r image.Rectangle, src *image.Uniform, mask *image.Alpha, mp image.Point) {
   461  	i0 := dst.PixOffset(r.Min.X, r.Min.Y)
   462  	i1 := i0 + r.Dx()*4
   463  	mi0 := mask.PixOffset(mp.X, mp.Y)
   464  	sr, sg, sb, sa := src.RGBA()
   465  	for y, my := r.Min.Y, mp.Y; y != r.Max.Y; y, my = y+1, my+1 {
   466  		for i, mi := i0, mi0; i < i1; i, mi = i+4, mi+1 {
   467  			ma := uint32(mask.Pix[mi])
   468  			if ma == 0 {
   469  				continue
   470  			}
   471  			ma |= ma << 8
   472  
   473  			dr := uint32(dst.Pix[i+0])
   474  			dg := uint32(dst.Pix[i+1])
   475  			db := uint32(dst.Pix[i+2])
   476  			da := uint32(dst.Pix[i+3])
   477  
   478  			// The 0x101 is here for the same reason as in drawRGBA.
   479  			a := (m - (sa * ma / m)) * 0x101
   480  
   481  			dst.Pix[i+0] = uint8((dr*a + sr*ma) / m >> 8)
   482  			dst.Pix[i+1] = uint8((dg*a + sg*ma) / m >> 8)
   483  			dst.Pix[i+2] = uint8((db*a + sb*ma) / m >> 8)
   484  			dst.Pix[i+3] = uint8((da*a + sa*ma) / m >> 8)
   485  		}
   486  		i0 += dst.Stride
   487  		i1 += dst.Stride
   488  		mi0 += mask.Stride
   489  	}
   490  }
   491  
   492  func drawRGBA(dst *image.RGBA, r image.Rectangle, src image.Image, sp image.Point, mask image.Image, mp image.Point, op Op) {
   493  	x0, x1, dx := r.Min.X, r.Max.X, 1
   494  	y0, y1, dy := r.Min.Y, r.Max.Y, 1
   495  	if image.Image(dst) == src && r.Overlaps(r.Add(sp.Sub(r.Min))) {
   496  		if sp.Y < r.Min.Y || sp.Y == r.Min.Y && sp.X < r.Min.X {
   497  			x0, x1, dx = x1-1, x0-1, -1
   498  			y0, y1, dy = y1-1, y0-1, -1
   499  		}
   500  	}
   501  
   502  	sy := sp.Y + y0 - r.Min.Y
   503  	my := mp.Y + y0 - r.Min.Y
   504  	sx0 := sp.X + x0 - r.Min.X
   505  	mx0 := mp.X + x0 - r.Min.X
   506  	sx1 := sx0 + (x1 - x0)
   507  	i0 := dst.PixOffset(x0, y0)
   508  	di := dx * 4
   509  	for y := y0; y != y1; y, sy, my = y+dy, sy+dy, my+dy {
   510  		for i, sx, mx := i0, sx0, mx0; sx != sx1; i, sx, mx = i+di, sx+dx, mx+dx {
   511  			ma := uint32(m)
   512  			if mask != nil {
   513  				_, _, _, ma = mask.At(mx, my).RGBA()
   514  			}
   515  			sr, sg, sb, sa := src.At(sx, sy).RGBA()
   516  			if op == Over {
   517  				dr := uint32(dst.Pix[i+0])
   518  				dg := uint32(dst.Pix[i+1])
   519  				db := uint32(dst.Pix[i+2])
   520  				da := uint32(dst.Pix[i+3])
   521  
   522  				// dr, dg, db and da are all 8-bit color at the moment, ranging in [0,255].
   523  				// We work in 16-bit color, and so would normally do:
   524  				// dr |= dr << 8
   525  				// and similarly for dg, db and da, but instead we multiply a
   526  				// (which is a 16-bit color, ranging in [0,65535]) by 0x101.
   527  				// This yields the same result, but is fewer arithmetic operations.
   528  				a := (m - (sa * ma / m)) * 0x101
   529  
   530  				dst.Pix[i+0] = uint8((dr*a + sr*ma) / m >> 8)
   531  				dst.Pix[i+1] = uint8((dg*a + sg*ma) / m >> 8)
   532  				dst.Pix[i+2] = uint8((db*a + sb*ma) / m >> 8)
   533  				dst.Pix[i+3] = uint8((da*a + sa*ma) / m >> 8)
   534  
   535  			} else {
   536  				dst.Pix[i+0] = uint8(sr * ma / m >> 8)
   537  				dst.Pix[i+1] = uint8(sg * ma / m >> 8)
   538  				dst.Pix[i+2] = uint8(sb * ma / m >> 8)
   539  				dst.Pix[i+3] = uint8(sa * ma / m >> 8)
   540  			}
   541  		}
   542  		i0 += dy * dst.Stride
   543  	}
   544  }
   545  
   546  // clamp clamps i to the interval [0, 0xffff].
   547  func clamp(i int32) int32 {
   548  	if i < 0 {
   549  		return 0
   550  	}
   551  	if i > 0xffff {
   552  		return 0xffff
   553  	}
   554  	return i
   555  }
   556  
   557  func drawPaletted(dst Image, r image.Rectangle, src image.Image, sp image.Point, floydSteinberg bool) {
   558  	// TODO(nigeltao): handle the case where the dst and src overlap.
   559  	// Does it even make sense to try and do Floyd-Steinberg whilst
   560  	// walking the image backward (right-to-left bottom-to-top)?
   561  
   562  	// If dst is an *image.Paletted, we have a fast path for dst.Set and
   563  	// dst.At. The dst.Set equivalent is a batch version of the algorithm
   564  	// used by color.Palette's Index method in image/color/color.go, plus
   565  	// optional Floyd-Steinberg error diffusion.
   566  	palette, pix, stride := [][3]int32(nil), []byte(nil), 0
   567  	if p, ok := dst.(*image.Paletted); ok {
   568  		palette = make([][3]int32, len(p.Palette))
   569  		for i, col := range p.Palette {
   570  			r, g, b, _ := col.RGBA()
   571  			palette[i][0] = int32(r)
   572  			palette[i][1] = int32(g)
   573  			palette[i][2] = int32(b)
   574  		}
   575  		pix, stride = p.Pix[p.PixOffset(r.Min.X, r.Min.Y):], p.Stride
   576  	}
   577  
   578  	// quantErrorCurr and quantErrorNext are the Floyd-Steinberg quantization
   579  	// errors that have been propagated to the pixels in the current and next
   580  	// rows. The +2 simplifies calculation near the edges.
   581  	var quantErrorCurr, quantErrorNext [][3]int32
   582  	if floydSteinberg {
   583  		quantErrorCurr = make([][3]int32, r.Dx()+2)
   584  		quantErrorNext = make([][3]int32, r.Dx()+2)
   585  	}
   586  
   587  	// Loop over each source pixel.
   588  	out := color.RGBA64{A: 0xffff}
   589  	for y := 0; y != r.Dy(); y++ {
   590  		for x := 0; x != r.Dx(); x++ {
   591  			// er, eg and eb are the pixel's R,G,B values plus the
   592  			// optional Floyd-Steinberg error.
   593  			sr, sg, sb, _ := src.At(sp.X+x, sp.Y+y).RGBA()
   594  			er, eg, eb := int32(sr), int32(sg), int32(sb)
   595  			if floydSteinberg {
   596  				er = clamp(er + quantErrorCurr[x+1][0]/16)
   597  				eg = clamp(eg + quantErrorCurr[x+1][1]/16)
   598  				eb = clamp(eb + quantErrorCurr[x+1][2]/16)
   599  			}
   600  
   601  			if palette != nil {
   602  				// Find the closest palette color in Euclidean R,G,B space: the
   603  				// one that minimizes sum-squared-difference. We shift by 1 bit
   604  				// to avoid potential uint32 overflow in sum-squared-difference.
   605  				// TODO(nigeltao): consider smarter algorithms.
   606  				bestIndex, bestSSD := 0, uint32(1<<32-1)
   607  				for index, p := range palette {
   608  					delta := (er - p[0]) >> 1
   609  					ssd := uint32(delta * delta)
   610  					delta = (eg - p[1]) >> 1
   611  					ssd += uint32(delta * delta)
   612  					delta = (eb - p[2]) >> 1
   613  					ssd += uint32(delta * delta)
   614  					if ssd < bestSSD {
   615  						bestIndex, bestSSD = index, ssd
   616  						if ssd == 0 {
   617  							break
   618  						}
   619  					}
   620  				}
   621  				pix[y*stride+x] = byte(bestIndex)
   622  
   623  				if !floydSteinberg {
   624  					continue
   625  				}
   626  				er -= int32(palette[bestIndex][0])
   627  				eg -= int32(palette[bestIndex][1])
   628  				eb -= int32(palette[bestIndex][2])
   629  
   630  			} else {
   631  				out.R = uint16(er)
   632  				out.G = uint16(eg)
   633  				out.B = uint16(eb)
   634  				// The third argument is &out instead of out (and out is
   635  				// declared outside of the inner loop) to avoid the implicit
   636  				// conversion to color.Color here allocating memory in the
   637  				// inner loop if sizeof(color.RGBA64) > sizeof(uintptr).
   638  				dst.Set(r.Min.X+x, r.Min.Y+y, &out)
   639  
   640  				if !floydSteinberg {
   641  					continue
   642  				}
   643  				sr, sg, sb, _ = dst.At(r.Min.X+x, r.Min.Y+y).RGBA()
   644  				er -= int32(sr)
   645  				eg -= int32(sg)
   646  				eb -= int32(sb)
   647  			}
   648  
   649  			// Propagate the Floyd-Steinberg quantization error.
   650  			quantErrorNext[x+0][0] += er * 3
   651  			quantErrorNext[x+0][1] += eg * 3
   652  			quantErrorNext[x+0][2] += eb * 3
   653  			quantErrorNext[x+1][0] += er * 5
   654  			quantErrorNext[x+1][1] += eg * 5
   655  			quantErrorNext[x+1][2] += eb * 5
   656  			quantErrorNext[x+2][0] += er * 1
   657  			quantErrorNext[x+2][1] += eg * 1
   658  			quantErrorNext[x+2][2] += eb * 1
   659  			quantErrorCurr[x+2][0] += er * 7
   660  			quantErrorCurr[x+2][1] += eg * 7
   661  			quantErrorCurr[x+2][2] += eb * 7
   662  		}
   663  
   664  		// Recycle the quantization error buffers.
   665  		if floydSteinberg {
   666  			quantErrorCurr, quantErrorNext = quantErrorNext, quantErrorCurr
   667  			for i := range quantErrorNext {
   668  				quantErrorNext[i] = [3]int32{}
   669  			}
   670  		}
   671  	}
   672  }