Пример #1
0
func resize(image *vips.Image, iw, ih int, fastResize bool, blurSigma float64, sharpen bool) error {
	m := format.MetadataImage(image)

	// Interpolation of RGB values with an alpha channel isn't safe
	// unless the values are pre-multiplied. Undo this later.
	// This also flattens fully transparent pixels to black.
	premultiply := image.HasAlpha()
	if premultiply {
		if err := image.Premultiply(); err != nil {
			return err
		}
	}

	// A box filter will quickly get us within 2x of the final size, at some quality cost.
	if fastResize {
		// Shrink factors can be passed independently here, which
		// may not be sane since Resize()'s blur and sharpening
		// steps expect a normal aspect ratio.
		wshrink := math.Floor(float64(m.Width) / float64(iw))
		hshrink := math.Floor(float64(m.Height) / float64(ih))
		if wshrink >= 2 || hshrink >= 2 {
			// Shrink rounds down the number of pixels.
			if err := image.Shrink(wshrink, hshrink); err != nil {
				return err
			}
			m = format.MetadataImage(image)
		}
	}

	// If necessary, do a high-quality resize to scale to final size.
	if iw < m.Width || ih < m.Height {
		// Vips 8.3 sometimes produces 1px smaller images than desired without the rounding help here.
		if err := image.Resize((float64(iw)+vips.ResizeOffset)/float64(m.Width), (float64(ih)+vips.ResizeOffset)/float64(m.Height)); err != nil {
			return err
		}
	}

	if blurSigma > 0.0 {
		if err := image.Gaussblur(blurSigma); err != nil {
			return err
		}
	}

	if sharpen {
		if err := image.MildSharpen(); err != nil {
			return err
		}
	}

	// Unpremultiply after all operations that touch adjacent pixels.
	if premultiply {
		if err := image.Unpremultiply(); err != nil {
			return err
		}
	}

	return nil
}
Пример #2
0
func crop(image *vips.Image, ow, oh int) error {
	m := format.MetadataImage(image)

	// If we have nothing to do, return.
	if ow == m.Width && oh == m.Height {
		return nil
	}

	// Center horizontally
	x := (m.Width - ow + 1) / 2
	// Assume faces are higher up vertically
	y := (m.Height - oh + 1) / 4

	if x < 0 || y < 0 {
		panic("Bad crop offsets!")
	}

	return image.ExtractArea(m.Orientation.Crop(ow, oh, x, y, m.Width, m.Height))
}