thumbnail.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /*
  2. Copyright (c) 2012, Jan Schlicht <jan.schlicht@gmail.com>
  3. Permission to use, copy, modify, and/or distribute this software for any purpose
  4. with or without fee is hereby granted, provided that the above copyright notice
  5. and this permission notice appear in all copies.
  6. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  7. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  8. FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  9. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  10. OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  11. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  12. THIS SOFTWARE.
  13. */
  14. package resize
  15. import (
  16. "image"
  17. )
  18. // Thumbnail will downscale provided image to max width and height preserving
  19. // original aspect ratio and using the interpolation function interp.
  20. // It will return original image, without processing it, if original sizes
  21. // are already smaller than provided constraints.
  22. func Thumbnail(maxWidth, maxHeight uint, img image.Image, interp InterpolationFunction) image.Image {
  23. origBounds := img.Bounds()
  24. origWidth := uint(origBounds.Dx())
  25. origHeight := uint(origBounds.Dy())
  26. newWidth, newHeight := origWidth, origHeight
  27. // Return original image if it have same or smaller size as constraints
  28. if maxWidth >= origWidth && maxHeight >= origHeight {
  29. return img
  30. }
  31. // Preserve aspect ratio
  32. if origWidth > maxWidth {
  33. newHeight = uint(origHeight * maxWidth / origWidth)
  34. if newHeight < 1 {
  35. newHeight = 1
  36. }
  37. newWidth = maxWidth
  38. }
  39. if newHeight > maxHeight {
  40. newWidth = uint(newWidth * maxHeight / newHeight)
  41. if newWidth < 1 {
  42. newWidth = 1
  43. }
  44. newHeight = maxHeight
  45. }
  46. return Resize(newWidth, newHeight, img, interp)
  47. }