package main

import (
	"image"
	"image/draw"

	"github.com/nfnt/resize"
	"opslag.de/schobers/tins2020/img"
)

func crop(path string, crop rect, size *point) error {
	src, err := img.DecodeImage(path)
	if err != nil {
		return err
	}
	srcRect := image.Rect(crop.min.x, crop.min.y, crop.max.x, crop.max.y)
	dstRect := image.Rect(0, 0, crop.max.x-crop.min.x, crop.max.y-crop.min.y)
	dst := image.NewRGBA(dstRect)
	draw.Draw(dst, dstRect, src, srcRect.Min, draw.Src)
	if size == nil {
		return img.EncodePNG(path, dst)
	}

	resized := resize.Resize(uint(size.x), uint(size.y), dst, resize.Bilinear)
	return img.EncodePNG(path, resized)
}