Code refactoring

This commit is contained in:
esimov
2018-01-17 10:52:56 +02:00
parent 24b25e8168
commit af88c26f90
3 changed files with 92 additions and 90 deletions

View File

@@ -8,13 +8,17 @@ import (
"io"
"os"
"image/jpeg"
"github.com/pkg/errors"
)
// SeamCarver is an interface that Carver uses to implement the Resize function.
// It takes an image and the output as parameters and returns the resized image.
type SeamCarver interface {
Resize(*image.NRGBA) (image.Image, error)
}
// Processor options
type Carver struct {
Width int
Height int
Points []float64
type Processor struct {
SobelThreshold int
BlurRadius int
NewWidth int
@@ -22,20 +26,84 @@ type Carver struct {
Percentage bool
}
// Implement the Resize method of the Carver interface.
func Resize(s SeamCarver, img *image.NRGBA) (image.Image, error) {
return s.Resize(img)
}
// This is the main entry point which takes the source image
// and encodes the new, rescaled image into the output file.
func (p *Processor) Resize(img *image.NRGBA) (image.Image, error) {
var c *Carver = NewCarver(img.Bounds().Dx(), img.Bounds().Dy())
resize := func() {
width, height := img.Bounds().Max.X, img.Bounds().Max.Y
c = NewCarver(width, height)
c.ComputeSeams(img, p)
seams := c.FindLowestEnergySeams()
img = c.RemoveSeam(img, seams)
}
if p.Percentage {
// Calculate new sizes based on provided percentage.
nw := c.Width - int(float64(c.Width) - (float64(p.NewWidth)/100 * float64(c.Width)))
nh := c.Height - int(float64(c.Height) - (float64(p.NewHeight)/100 * float64(c.Height)))
// Resize image horizontally
for x := 0; x < nw; x++ {
resize()
}
// Resize image vertically
img = c.RotateImage90(img)
// Needs to update the slice width & height because of image rotation.
c.Width = img.Bounds().Dx()
c.Height = img.Bounds().Dy()
for y := 0; y < nh; y++ {
resize()
}
img = c.RotateImage270(img)
} else if p.NewWidth > 0 || p.NewHeight > 0 {
if p.NewWidth > 0 {
if p.NewWidth > c.Width {
err := errors.New("new width should be less than image width.")
return nil, err
}
for x := 0; x < p.NewWidth; x++ {
resize()
}
}
if p.NewHeight > 0 {
if p.NewHeight > c.Height {
err := errors.New("new height should be less than image height.")
return nil, err
}
img = c.RotateImage90(img)
// Needs to update the slice width & height because of image rotation
// otherwise the new image will be cut off.
c.Width = img.Bounds().Dx()
c.Height = img.Bounds().Dy()
for y := 0; y < p.NewHeight; y++ {
resize()
}
img = c.RotateImage270(img)
}
}
return img, nil
}
// Process is the main entry point for the image resize operation.
func (c *Carver) Process(file io.Reader, output string) (*os.File, error) {
func (p *Processor) Process(file io.Reader, output string) (*os.File, error) {
src, _, err := image.Decode(file)
if err != nil {
return nil, err
}
img := imgToNRGBA(src)
res, err := Resize(c, img)
//sobel := SobelFilter(Grayscale(img), float64(p.SobelThreshold))
res, err := Resize(p, img)
if err != nil {
return nil, err
}