thumbnail.go

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