This commit is contained in:
Tomas Aparicio 2015-04-05 22:01:48 +02:00
parent 885b315035
commit d471c49348
5 changed files with 168 additions and 47 deletions

View file

@ -16,8 +16,15 @@ const (
NOHALO
)
const (
CENTRE Gravity = iota
NORTH
EAST
SOUTH
WEST
)
func Resize(buf []byte, o Options) ([]byte, error) {
// detect (if possible) the file type
defer C.vips_thread_shutdown()
image, err := vipsRead(buf)
@ -34,7 +41,6 @@ func Resize(buf []byte, o Options) ([]byte, error) {
inWidth := int(image.Xsize)
inHeight := int(image.Ysize)
// crop
if o.Crop {
left, top := calculateCrop(inWidth, inHeight, o.Width, o.Height, o.Gravity)
o.Width = int(math.Min(float64(inWidth), float64(o.Width)))
@ -45,9 +51,24 @@ func Resize(buf []byte, o Options) ([]byte, error) {
}
}
// rotate
rotation, flip := calculateRotationAndFlip(image, o.Rotate)
if flip {
o.Flip = HORIZONTAL
}
if rotation != D0 {
o.Rotate = rotation
}
if o.Rotate > 0 {
image, err = Rotate(image, Rotation{o.Rotate})
rotation := calculateRotation(o.Rotate)
image, err = vipsRotate(image, rotation)
if err != nil {
return nil, err
}
}
if o.Flip > 0 {
image, err = vipsFlip(image, o.Flip)
if err != nil {
return nil, err
}
@ -62,21 +83,9 @@ func Resize(buf []byte, o Options) ([]byte, error) {
return buf, nil
}
func Rotate(image *C.struct__VipsImage, r Rotation) (*C.struct__VipsImage, error) {
//vips := &Vips{}
return vipsRotate(image, r.calculate())
}
const (
CENTRE Gravity = iota
NORTH
EAST
SOUTH
WEST
)
func calculateCrop(inWidth, inHeight, outWidth, outHeight int, gravity Gravity) (int, int) {
left, top := 0, 0
switch gravity {
case NORTH:
left = (inWidth - outWidth + 1) / 2
@ -92,5 +101,58 @@ func calculateCrop(inWidth, inHeight, outWidth, outHeight int, gravity Gravity)
left = (inWidth - outWidth + 1) / 2
top = (inHeight - outHeight + 1) / 2
}
return left, top
}
func calculateRotationAndFlip(image *C.struct__VipsImage, angle Angle) (Angle, bool) {
rotate := D0
flip := false
if angle == -1 {
switch vipsExifOrientation(image) {
case 6:
rotate = D90
break
case 3:
rotate = D180
break
case 8:
rotate = D270
break
case 2:
flip = true
break // flip 1
case 7:
flip = true
rotate = D90
break // flip 6
case 4:
flip = true
rotate = D180
break // flip 3
case 5:
flip = true
rotate = D270
break // flip 8
}
} else {
if angle == 90 {
rotate = D90
} else if angle == 180 {
rotate = D180
} else if angle == 270 {
rotate = D270
}
}
return rotate, flip
}
func calculateRotation(angle Angle) Angle {
divisor := angle % 90
if divisor != 0 {
angle = angle - divisor
}
return angle
}