extend.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package processing
  2. import (
  3. "github.com/imgproxy/imgproxy/v3/imagedata"
  4. "github.com/imgproxy/imgproxy/v3/imath"
  5. "github.com/imgproxy/imgproxy/v3/options"
  6. "github.com/imgproxy/imgproxy/v3/vips"
  7. )
  8. func extendImage(img *vips.Image, resultWidth, resultHeight int, opts *options.ExtendOptions, offsetScale float64, extendAr bool) error {
  9. if !opts.Enabled || (resultWidth <= img.Width() && resultHeight <= img.Height()) || resultWidth == 0 || resultHeight == 0 {
  10. return nil
  11. }
  12. if extendAr && resultWidth > img.Width() && resultHeight > img.Height() {
  13. diffW := float64(resultWidth) / float64(img.Width())
  14. diffH := float64(resultHeight) / float64(img.Height())
  15. switch {
  16. case diffH > diffW:
  17. resultHeight = imath.Scale(img.Width(), float64(resultHeight)/float64(resultWidth))
  18. resultWidth = img.Width()
  19. case diffW > diffH:
  20. resultWidth = imath.Scale(img.Height(), float64(resultWidth)/float64(resultHeight))
  21. resultHeight = img.Height()
  22. default:
  23. // The image has the requested arpect ratio
  24. return nil
  25. }
  26. }
  27. offX, offY := calcPosition(resultWidth, resultHeight, img.Width(), img.Height(), &opts.Gravity, offsetScale, false)
  28. return img.Embed(resultWidth, resultHeight, offX, offY)
  29. }
  30. func extend(pctx *pipelineContext, img *vips.Image, po *options.ProcessingOptions, imgdata *imagedata.ImageData) error {
  31. resultWidth, resultHeight := resultSize(po, pctx.dprScale)
  32. return extendImage(img, resultWidth, resultHeight, &po.Extend, pctx.dprScale, false)
  33. }
  34. func extendAspectRatio(pctx *pipelineContext, img *vips.Image, po *options.ProcessingOptions, imgdata *imagedata.ImageData) error {
  35. resultWidth, resultHeight := resultSize(po, pctx.dprScale)
  36. return extendImage(img, resultWidth, resultHeight, &po.ExtendAspectRatio, pctx.dprScale, true)
  37. }