paste.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package imaging
  2. import (
  3. "image"
  4. )
  5. // Paste pastes the img image to the background image at the specified position and returns the combined image.
  6. func Paste(background, img image.Image, pos image.Point) *image.NRGBA {
  7. src := toNRGBA(img)
  8. dst := Clone(background) // cloned image bounds start at (0, 0)
  9. startPt := pos.Sub(background.Bounds().Min) // so we should translate start point
  10. endPt := startPt.Add(src.Bounds().Size())
  11. pasteBounds := image.Rectangle{startPt, endPt}
  12. if dst.Bounds().Overlaps(pasteBounds) {
  13. intersectBounds := dst.Bounds().Intersect(pasteBounds)
  14. rowSize := intersectBounds.Dx() * 4
  15. numRows := intersectBounds.Dy()
  16. srcStartX := intersectBounds.Min.X - pasteBounds.Min.X
  17. srcStartY := intersectBounds.Min.Y - pasteBounds.Min.Y
  18. i0 := dst.PixOffset(intersectBounds.Min.X, intersectBounds.Min.Y)
  19. j0 := src.PixOffset(srcStartX, srcStartY)
  20. di := dst.Stride
  21. dj := src.Stride
  22. for row := 0; row < numRows; row++ {
  23. copy(dst.Pix[i0:i0+rowSize], src.Pix[j0:j0+rowSize])
  24. i0 += di
  25. j0 += dj
  26. }
  27. }
  28. return dst
  29. }
  30. // PasteCenter pastes the img image to the center of the background image and returns the combined image.
  31. func PasteCenter(background, img image.Image) *image.NRGBA {
  32. bgBounds := background.Bounds()
  33. bgW := bgBounds.Dx()
  34. bgH := bgBounds.Dy()
  35. bgMinX := bgBounds.Min.X
  36. bgMinY := bgBounds.Min.Y
  37. centerX := bgMinX + bgW/2
  38. centerY := bgMinY + bgH/2
  39. x0 := centerX - img.Bounds().Dx()/2
  40. y0 := centerY - img.Bounds().Dy()/2
  41. return Paste(background, img, image.Pt(x0, y0))
  42. }