thumbnail.go 989 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. // Copyright 2011 The Graphics-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. package graphics
  5. import (
  6. "image"
  7. "image/draw"
  8. )
  9. // Thumbnail scales and crops src so it fits in dst.
  10. func Thumbnail(dst draw.Image, src image.Image) error {
  11. // Scale down src in the dimension that is closer to dst.
  12. sb := src.Bounds()
  13. db := dst.Bounds()
  14. rx := float64(sb.Dx()) / float64(db.Dx())
  15. ry := float64(sb.Dy()) / float64(db.Dy())
  16. var b image.Rectangle
  17. if rx < ry {
  18. b = image.Rect(0, 0, db.Dx(), int(float64(sb.Dy())/rx))
  19. } else {
  20. b = image.Rect(0, 0, int(float64(sb.Dx())/ry), db.Dy())
  21. }
  22. buf := image.NewRGBA(b)
  23. if err := Scale(buf, src); err != nil {
  24. return err
  25. }
  26. // Crop.
  27. // TODO(crawshaw): improve on center-alignment.
  28. var pt image.Point
  29. if rx < ry {
  30. pt.Y = (b.Dy() - db.Dy()) / 2
  31. } else {
  32. pt.X = (b.Dx() - db.Dx()) / 2
  33. }
  34. draw.Draw(dst, db, buf, pt, draw.Src)
  35. return nil
  36. }