Пример #1
0
// Smart crop given image file & write it to io.Writer
func smartCrop(w io.Writer, r io.Reader, size []int) error {
	img, mimetype, err := image.Decode(r)
	if size == nil || err != nil {
		io.Copy(w, r)
		return nil
	}

	size = setMaxSize(fitToActualSize(&img, size))
	crop, err := smartcrop.SmartCrop(&img, size[0], size[1])
	if err != nil {
		io.Copy(w, r)
		return nil
	}

	croppedBuffer := image.NewRGBA(image.Rect(0, 0, crop.Width, crop.Height))
	draw.Draw(
		croppedBuffer,
		croppedBuffer.Bounds(),
		img,
		image.Point{crop.X, crop.Y},
		draw.Src,
	)

	dst := image.NewRGBA(image.Rect(0, 0, size[0], size[1]))
	graphics.Scale(dst, croppedBuffer)
	return writeByMimetype(w, dst, mimetype)
}
Пример #2
0
func getFillCrop(src image.Image, targetRatio float32) (smartcrop.Crop, error) {
	srcWidth := src.Bounds().Size().X
	srcHeight := src.Bounds().Size().Y
	newWidth := srcWidth
	newHeight := srcHeight
	srcRatio := float32(srcWidth) / float32(srcHeight)
	if srcRatio > targetRatio {
		// width stays the same
		newHeight = int(float32(srcWidth) / targetRatio)
	}
	if srcRatio < targetRatio {
		// height stays the same
		newWidth = int(float32(srcHeight) * targetRatio)
	}

	return smartcrop.SmartCrop(&src, newWidth, newHeight)
}