소스 검색

Refine processing.ProcessImage

DarthSim 1 개월 전
부모
커밋
ac48257772
5개의 변경된 파일471개의 추가작업 그리고 266개의 파일을 삭제
  1. 355 263
      processing/processing.go
  2. 74 0
      processing/save_fit_bytes.go
  3. 15 1
      vips/vips.c
  4. 25 1
      vips/vips.go
  5. 2 1
      vips/vips.h

+ 355 - 263
processing/processing.go

@@ -18,6 +18,8 @@ import (
 	"github.com/imgproxy/imgproxy/v3/vips"
 )
 
+// The main processing pipeline (without finalization).
+// Applied to non-animated images and individual frames of animated images.
 var mainPipeline = pipeline{
 	vectorGuardScale,
 	trim,
@@ -37,64 +39,196 @@ var mainPipeline = pipeline{
 	watermark,
 }
 
+// The finalization pipeline.
+// Applied right before saving the image.
 var finalizePipeline = pipeline{
 	colorspaceToResult,
 	stripMetadata,
 }
 
-func isImageTypePreferred(imgtype imagetype.Type) bool {
+func ValidatePreferredFormats() error {
+	filtered := config.PreferredFormats[:0]
+
 	for _, t := range config.PreferredFormats {
-		if imgtype == t {
-			return true
+		if !vips.SupportsSave(t) {
+			log.Warnf("%s can't be a preferred format as it's saving is not supported", t)
+		} else {
+			filtered = append(filtered, t)
 		}
 	}
 
-	return false
+	if len(filtered) == 0 {
+		return errors.New("no supported preferred formats specified")
+	}
+
+	config.PreferredFormats = filtered
+
+	return nil
 }
 
-func findBestFormat(srcType imagetype.Type, animated, expectAlpha bool) imagetype.Type {
-	for _, t := range config.PreferredFormats {
-		if animated && !t.SupportsAnimationSave() {
-			continue
-		}
+// Result holds the result of image processing.
+type Result struct {
+	OutData      imagedata.ImageData
+	OriginWidth  int
+	OriginHeight int
+	ResultWidth  int
+	ResultHeight int
+}
+
+// ProcessImage processes the image according to the provided processing options
+// and returns a [Result] that includes the processed image data and dimensions.
+//
+// The provided processing options may be modified during processing.
+func ProcessImage(
+	ctx context.Context,
+	imgdata imagedata.ImageData,
+	po *options.ProcessingOptions,
+) (*Result, error) {
+	runtime.LockOSThread()
+	defer runtime.UnlockOSThread()
+
+	defer vips.Cleanup()
+
+	img := new(vips.Image)
+	defer img.Clear()
+
+	// Load a single page/frame of the image so we can analyze it
+	// and decide how to process it further
+	thumbnailLoaded, err := initialLoadImage(img, imgdata, po.EnforceThumbnail)
+	if err != nil {
+		return nil, err
+	}
+
+	// Let's check if we should skip standard processing
+	if shouldSkipStandardProcessing(imgdata.Format(), po) {
+		return skipStandardProcessing(img, imgdata, po)
+	}
+
+	// Check if we expect image to be processed as animated.
+	// If MaxAnimationFrames is 1, we never process as animated since we can only
+	// process a single frame.
+	animated := po.SecurityOptions.MaxAnimationFrames > 1 &&
+		img.IsAnimated()
 
-		if expectAlpha && !t.SupportsAlpha() {
-			continue
+	// Determine output format and check if it's supported.
+	// The determined format is stored in po.Format.
+	if err = determineOutputFormat(img, imgdata, po, animated); err != nil {
+		return nil, err
+	}
+
+	// Now, as we know the output format, we know for sure if the image
+	// should be processed as animated
+	animated = animated && po.Format.SupportsAnimationSave()
+
+	// Load required number of frames/pages for processing
+	// and remove animation-related data if not animated.
+	// Don't reload if we initially loaded a thumbnail.
+	if !thumbnailLoaded {
+		if err = reloadImageForProcessing(img, imgdata, po, animated); err != nil {
+			return nil, err
 		}
+	}
 
-		return t
+	// Check image dimensions and number of frames for security reasons
+	originWidth, originHeight, err := checkImageSize(img, imgdata.Format(), po.SecurityOptions)
+	if err != nil {
+		return nil, err
 	}
 
-	return config.PreferredFormats[0]
-}
+	// Transform the image (resize, crop, etc)
+	if err = transformImage(ctx, img, po, imgdata, animated); err != nil {
+		return nil, err
+	}
 
-func ValidatePreferredFormats() error {
-	filtered := config.PreferredFormats[:0]
+	// Finalize the image (colorspace conversion, metadata stripping, etc)
+	if err = finalizePipeline.Run(ctx, img, po, imgdata); err != nil {
+		return nil, err
+	}
 
-	for _, t := range config.PreferredFormats {
-		if !vips.SupportsSave(t) {
-			log.Warnf("%s can't be a preferred format as it's saving is not supported", t)
+	outData, err := saveImage(ctx, img, po)
+	if err != nil {
+		return nil, err
+	}
+
+	resultWidth, resultHeight, _ := getImageSize(img)
+
+	return &Result{
+		OutData:      outData,
+		OriginWidth:  originWidth,
+		OriginHeight: originHeight,
+		ResultWidth:  resultWidth,
+		ResultHeight: resultHeight,
+	}, nil
+}
+
+// initialLoadImage loads a single page/frame of the image.
+// If the image format supports thumbnails and thumbnail loading is enforced,
+// it tries to load the thumbnail first.
+func initialLoadImage(
+	img *vips.Image,
+	imgdata imagedata.ImageData,
+	enforceThumbnail bool,
+) (bool, error) {
+	if enforceThumbnail && imgdata.Format().SupportsThumbnail() {
+		if err := img.LoadThumbnail(imgdata); err == nil {
+			return true, nil
 		} else {
-			filtered = append(filtered, t)
+			log.Debugf("Can't load thumbnail: %s", err)
 		}
 	}
 
-	if len(filtered) == 0 {
-		return errors.New("no supported preferred formats specified")
+	return false, img.Load(imgdata, 1, 1.0, 1)
+}
+
+// reloadImageForProcessing reloads the image for processing.
+// For animated images, it loads all frames up to MaxAnimationFrames.
+func reloadImageForProcessing(
+	img *vips.Image,
+	imgdata imagedata.ImageData,
+	po *options.ProcessingOptions,
+	asAnimated bool,
+) error {
+	// If we are going to process the image as animated, we need to load all frames
+	// up to MaxAnimationFrames
+	if asAnimated {
+		frames := min(img.Pages(), po.SecurityOptions.MaxAnimationFrames)
+		return img.Load(imgdata, 1, 1.0, frames)
 	}
 
-	config.PreferredFormats = filtered
+	// Otherwise, we just need to remove any animation-related data
+	return img.RemoveAnimation()
+}
 
-	return nil
+// checkImageSize checks the image dimensions and number of frames against security options.
+// It returns the image width, height and a security check error, if any.
+func checkImageSize(
+	img *vips.Image,
+	imgtype imagetype.Type,
+	secops security.Options,
+) (int, int, error) {
+	width, height, frames := getImageSize(img)
+
+	if imgtype.IsVector() {
+		// We don't check vector image dimensions as we can render it in any size
+		return width, height, nil
+	}
+
+	err := security.CheckDimensions(width, height, frames, secops)
+
+	return width, height, err
 }
 
-func getImageSize(img *vips.Image) (int, int) {
+// getImageSize returns the width and height of the image, taking into account
+// orientation and animation.
+func getImageSize(img *vips.Image) (int, int, int) {
 	width, height := img.Width(), img.Height()
+	frames := 1
 
 	if img.IsAnimated() {
 		// Animated images contain multiple frames, and libvips loads them stacked vertically.
 		// We want to return the size of a single frame
 		height = img.PageHeight()
+		frames = img.PagesLoaded()
 	}
 
 	// If the image is rotated by 90 or 270 degrees, we need to swap width and height
@@ -103,49 +237,198 @@ func getImageSize(img *vips.Image) (int, int) {
 		width, height = height, width
 	}
 
-	return width, height
+	return width, height, frames
 }
 
-func transformAnimated(ctx context.Context, img *vips.Image, po *options.ProcessingOptions, imgdata imagedata.ImageData) error {
-	if po.Trim.Enabled {
-		log.Warning("Trim is not supported for animated images")
-		po.Trim.Enabled = false
-	}
+// Returns true if image should not be processed as usual
+func shouldSkipStandardProcessing(inFormat imagetype.Type, po *options.ProcessingOptions) bool {
+	outFormat := po.Format
+	skipProcessingFormatEnabled := slices.Contains(po.SkipProcessingFormats, inFormat)
 
-	imgWidth := img.Width()
-	framesCount := min(img.Pages(), po.SecurityOptions.MaxAnimationFrames)
+	if inFormat == imagetype.SVG {
+		isOutUnknown := outFormat == imagetype.Unknown
 
-	frameHeight, err := img.GetInt("page-height")
+		switch {
+		case outFormat == imagetype.SVG:
+			return true
+		case isOutUnknown && !config.AlwaysRasterizeSvg:
+			return true
+		case isOutUnknown && config.AlwaysRasterizeSvg && skipProcessingFormatEnabled:
+			return true
+		default:
+			return false
+		}
+	} else {
+		return skipProcessingFormatEnabled && (inFormat == outFormat || outFormat == imagetype.Unknown)
+	}
+}
+
+// skipStandardProcessing skips standard image processing and returns the original image data.
+//
+// SVG images may be sanitized if configured to do so.
+func skipStandardProcessing(
+	img *vips.Image,
+	imgdata imagedata.ImageData,
+	po *options.ProcessingOptions,
+) (*Result, error) {
+	// Even if we skip standard processing, we still need to check image dimensions
+	// to not send an image bomb to the client
+	originWidth, originHeight, err := checkImageSize(img, imgdata.Format(), po.SecurityOptions)
 	if err != nil {
-		return err
+		return nil, err
 	}
 
-	// Double check dimensions because animated image has many frames
-	if err = security.CheckDimensions(imgWidth, frameHeight, framesCount, po.SecurityOptions); err != nil {
-		return err
+	// Even in this case, SVG is an exception
+	if imgdata.Format() == imagetype.SVG && config.SanitizeSvg {
+		sanitized, err := svg.Sanitize(imgdata)
+		if err != nil {
+			return nil, err
+		}
+
+		return &Result{
+			OutData:      sanitized,
+			OriginWidth:  originWidth,
+			OriginHeight: originHeight,
+			ResultWidth:  originWidth,
+			ResultHeight: originHeight,
+		}, nil
 	}
 
-	if img.Pages() > framesCount {
-		// Load only the needed frames
-		if err = img.Load(imgdata, 1, 1.0, framesCount); err != nil {
-			return err
+	// Return the original image
+	return &Result{
+		OutData:      imgdata,
+		OriginWidth:  originWidth,
+		OriginHeight: originHeight,
+		ResultWidth:  originWidth,
+		ResultHeight: originHeight,
+	}, nil
+}
+
+// determineOutputFormat determines the output image format based on the processing options
+// and image properties.
+//
+// It modifies the ProcessingOptions in place to set the output format.
+func determineOutputFormat(
+	img *vips.Image,
+	imgdata imagedata.ImageData,
+	po *options.ProcessingOptions,
+	animated bool,
+) error {
+	// Check if the image may have transparency
+	expectTransparency := !po.Flatten &&
+		(img.HasAlpha() || po.Padding.Enabled || po.Extend.Enabled)
+
+	switch {
+	case po.Format == imagetype.SVG:
+		// At this point we can't allow requested format to be SVG as we can't save SVGs
+		return newSaveFormatError(po.Format)
+	case po.Format == imagetype.Unknown:
+		switch {
+		case po.PreferJxl && !animated:
+			po.Format = imagetype.JXL
+		case po.PreferAvif && !animated:
+			po.Format = imagetype.AVIF
+		case po.PreferWebP:
+			po.Format = imagetype.WEBP
+		case isImageTypePreferred(imgdata.Format()):
+			po.Format = imgdata.Format()
+		default:
+			po.Format = findPreferredFormat(animated, expectTransparency)
+		}
+	case po.EnforceJxl && !animated:
+		po.Format = imagetype.JXL
+	case po.EnforceAvif && !animated:
+		po.Format = imagetype.AVIF
+	case po.EnforceWebP:
+		po.Format = imagetype.WEBP
+	}
+
+	if !vips.SupportsSave(po.Format) {
+		return newSaveFormatError(po.Format)
+	}
+
+	return nil
+}
+
+// isImageTypePreferred checks if the given image type is in the list of preferred formats.
+func isImageTypePreferred(imgtype imagetype.Type) bool {
+	return slices.Contains(config.PreferredFormats, imgtype)
+}
+
+// isImageTypeCompatible checks if the given image type is compatible with the image properties.
+func isImageTypeCompatible(imgtype imagetype.Type, animated, expectTransparency bool) bool {
+	if animated && !imgtype.SupportsAnimationSave() {
+		return false
+	}
+
+	if expectTransparency && !imgtype.SupportsAlpha() {
+		return false
+	}
+
+	return true
+}
+
+// findPreferredFormat finds a suitable preferred format based on image's properties.
+func findPreferredFormat(animated, expectTransparency bool) imagetype.Type {
+	for _, t := range config.PreferredFormats {
+		if isImageTypeCompatible(t, animated, expectTransparency) {
+			return t
 		}
 	}
 
+	return config.PreferredFormats[0]
+}
+
+func transformImage(
+	ctx context.Context,
+	img *vips.Image,
+	po *options.ProcessingOptions,
+	imgdata imagedata.ImageData,
+	asAnimated bool,
+) error {
+	if asAnimated {
+		return transformAnimated(ctx, img, po, imgdata)
+	}
+
+	return mainPipeline.Run(ctx, img, po, imgdata)
+}
+
+func transformAnimated(
+	ctx context.Context,
+	img *vips.Image,
+	po *options.ProcessingOptions,
+	imgdata imagedata.ImageData,
+) error {
+	if po.Trim.Enabled {
+		log.Warning("Trim is not supported for animated images")
+		po.Trim.Enabled = false
+	}
+
+	imgWidth := img.Width()
+	frameHeight := img.PageHeight()
+	framesCount := img.PagesLoaded()
+
+	// Get frame delays. We'll need to set them back later.
+	// If we don't have delay info, we'll set a default delay later.
 	delay, err := img.GetIntSliceDefault("delay", nil)
 	if err != nil {
 		return err
 	}
 
+	// Get loop count. We'll need to set it back later.
+	// 0 means infinite looping.
 	loop, err := img.GetIntDefault("loop", 0)
 	if err != nil {
 		return err
 	}
 
+	// Disable watermarking for individual frames.
+	// It's more efficient to apply watermark to all frames at once after they are processed.
 	watermarkEnabled := po.Watermark.Enabled
 	po.Watermark.Enabled = false
 	defer func() { po.Watermark.Enabled = watermarkEnabled }()
 
+	// Make a slice to hold processed frames and ensure they are cleared on function exit
 	frames := make([]*vips.Image, 0, framesCount)
 	defer func() {
 		for _, frame := range frames {
@@ -158,16 +441,22 @@ func transformAnimated(ctx context.Context, img *vips.Image, po *options.Process
 	for i := 0; i < framesCount; i++ {
 		frame := new(vips.Image)
 
+		// Extract an individual frame from the image.
+		// Libvips loads animated images as a single image with frames stacked vertically.
 		if err = img.Extract(frame, 0, i*frameHeight, imgWidth, frameHeight); err != nil {
 			return err
 		}
 
 		frames = append(frames, frame)
 
+		// Transform the frame using the main pipeline.
+		// We don't provide imgdata here to prevent scale-on-load.
 		if err = mainPipeline.Run(ctx, frame, po, nil); err != nil {
 			return err
 		}
 
+		// If the frame was scaled down, it's better to copy it to RAM
+		// to speed up further processing.
 		if r, _ := frame.GetIntDefault("imgproxy-scaled-down", 0); r == 1 {
 			if err = frame.CopyMemory(); err != nil {
 				return err
@@ -179,35 +468,42 @@ func transformAnimated(ctx context.Context, img *vips.Image, po *options.Process
 		}
 	}
 
+	// Join processed frames back into a single image.
 	if err = img.Arrayjoin(frames); err != nil {
 		return err
 	}
 
+	// Apply watermark to all frames at once if it was requested.
+	// This is much more efficient than applying watermark to individual frames.
 	if watermarkEnabled && imagedata.Watermark != nil {
+		// Get DPR scale to apply watermark correctly on HiDPI images.
+		// `imgproxy-dpr-scale` is set by the pipeline.
 		dprScale, derr := img.GetDoubleDefault("imgproxy-dpr-scale", 1.0)
 		if derr != nil {
 			dprScale = 1.0
 		}
 
-		if err = applyWatermark(img, imagedata.Watermark, &po.Watermark, dprScale, framesCount); err != nil {
+		if err = applyWatermark(
+			img, imagedata.Watermark, &po.Watermark, dprScale, framesCount,
+		); err != nil {
 			return err
 		}
 	}
 
-	if err = img.CastUchar(); err != nil {
-		return err
-	}
-
 	if len(delay) == 0 {
+		// if we don't have delay info, set it to 40ms for each frame (25 FPS).
 		delay = make([]int, framesCount)
 		for i := range delay {
 			delay[i] = 40
 		}
 	} else if len(delay) > framesCount {
+		// if we have more delay entries than frames, truncate it.
 		delay = delay[:framesCount]
 	}
 
+	// Mark the image as animated so img.Strip() doesn't remove animation data.
 	img.SetInt("imgproxy-is-animated", 1)
+	// Set animation data back.
 	img.SetInt("page-height", frames[0].Height())
 	img.SetIntSlice("delay", delay)
 	img.SetInt("loop", loop)
@@ -216,178 +512,13 @@ func transformAnimated(ctx context.Context, img *vips.Image, po *options.Process
 	return nil
 }
 
-func saveImageToFitBytes(ctx context.Context, po *options.ProcessingOptions, img *vips.Image) (imagedata.ImageData, error) {
-	var diff float64
-	quality := po.GetQuality()
-
-	if err := img.CopyMemory(); err != nil {
-		return nil, err
-	}
-
-	for {
-		imgdata, err := img.Save(po.Format, quality)
-		if err != nil {
-			return nil, err
-		}
-
-		size, err := imgdata.Size()
-		if err != nil {
-			return nil, err
-		}
-
-		if size <= po.MaxBytes || quality <= 10 {
-			return imgdata, err
-		}
-		imgdata.Close()
-
-		if err := server.CheckTimeout(ctx); err != nil {
-			return nil, err
-		}
-
-		delta := float64(size) / float64(po.MaxBytes)
-		switch {
-		case delta > 3:
-			diff = 0.25
-		case delta > 1.5:
-			diff = 0.5
-		default:
-			diff = 0.75
-		}
-		quality = int(float64(quality) * diff)
-	}
-}
-
-type Result struct {
-	OutData      imagedata.ImageData
-	OriginWidth  int
-	OriginHeight int
-	ResultWidth  int
-	ResultHeight int
-}
-
-func ProcessImage(ctx context.Context, imgdata imagedata.ImageData, po *options.ProcessingOptions) (*Result, error) {
-	runtime.LockOSThread()
-	defer runtime.UnlockOSThread()
-
-	defer vips.Cleanup()
-
-	animationSupport :=
-		po.SecurityOptions.MaxAnimationFrames > 1 &&
-			imgdata.Format().SupportsAnimationLoad() &&
-			(po.Format == imagetype.Unknown || po.Format.SupportsAnimationSave())
-
-	pages := 1
-	if animationSupport {
-		pages = -1
-	}
-
-	img := new(vips.Image)
-	defer img.Clear()
-
-	if po.EnforceThumbnail && imgdata.Format().SupportsThumbnail() {
-		if err := img.LoadThumbnail(imgdata); err != nil {
-			log.Debugf("Can't load thumbnail: %s", err)
-			// Failed to load thumbnail, rollback to the full image
-			if err := img.Load(imgdata, 1, 1.0, pages); err != nil {
-				return nil, err
-			}
-		}
-	} else {
-		if err := img.Load(imgdata, 1, 1.0, pages); err != nil {
-			return nil, err
-		}
-	}
-
-	originWidth, originHeight := getImageSize(img)
-
-	if !imgdata.Format().IsVector() {
-		if err := security.CheckDimensions(originWidth, originHeight, 1, po.SecurityOptions); err != nil {
-			return nil, err
-		}
-	}
-
-	// Let's check if we should skip standard processing
-	if shouldSkipStandardProcessing(imgdata.Format(), po) {
-		// Even in this case, SVG is an exception
-		if imgdata.Format() == imagetype.SVG && config.SanitizeSvg {
-			sanitized, err := svg.Sanitize(imgdata)
-			if err != nil {
-				return nil, err
-			}
-
-			return &Result{
-				OutData:      sanitized,
-				OriginWidth:  originWidth,
-				OriginHeight: originHeight,
-				ResultWidth:  originWidth,
-				ResultHeight: originHeight,
-			}, nil
-		}
-
-		// Return the original image
-		return &Result{
-			OutData:      imgdata,
-			OriginWidth:  originWidth,
-			OriginHeight: originHeight,
-			ResultWidth:  originWidth,
-			ResultHeight: originHeight,
-		}, nil
-	}
-
-	animated := img.IsAnimated()
-	expectAlpha := !po.Flatten && (img.HasAlpha() || po.Padding.Enabled || po.Extend.Enabled)
-
-	switch {
-	case po.Format == imagetype.SVG:
-		// At this point we can't allow requested format to be SVG as we can't save SVGs
-		return nil, newSaveFormatError(po.Format)
-	case po.Format == imagetype.Unknown:
-		switch {
-		case po.PreferJxl && !animated:
-			po.Format = imagetype.JXL
-		case po.PreferAvif && !animated:
-			po.Format = imagetype.AVIF
-		case po.PreferWebP:
-			po.Format = imagetype.WEBP
-		case isImageTypePreferred(imgdata.Format()):
-			po.Format = imgdata.Format()
-		default:
-			po.Format = findBestFormat(imgdata.Format(), animated, expectAlpha)
-		}
-	case po.EnforceJxl && !animated:
-		po.Format = imagetype.JXL
-	case po.EnforceAvif && !animated:
-		po.Format = imagetype.AVIF
-	case po.EnforceWebP:
-		po.Format = imagetype.WEBP
-	}
-
-	if !vips.SupportsSave(po.Format) {
-		return nil, newSaveFormatError(po.Format)
-	}
-
-	if po.Format.SupportsAnimationSave() && animated {
-		if err := transformAnimated(ctx, img, po, imgdata); err != nil {
-			return nil, err
-		}
-	} else {
-		if animated {
-			// We loaded animated image but the resulting format doesn't support
-			// animations, so we need to reload image as not animated
-			if err := img.Load(imgdata, 1, 1.0, 1); err != nil {
-				return nil, err
-			}
-		}
-
-		if err := mainPipeline.Run(ctx, img, po, imgdata); err != nil {
-			return nil, err
-		}
-	}
-
-	if err := finalizePipeline.Run(ctx, img, po, imgdata); err != nil {
-		return nil, err
-	}
-
+func saveImage(
+	ctx context.Context,
+	img *vips.Image,
+	po *options.ProcessingOptions,
+) (imagedata.ImageData, error) {
+	// AVIF has a minimal dimension of 16 pixels.
+	// If one of the dimensions is less, we need to switch to another format.
 	if po.Format == imagetype.AVIF && (img.Width() < 16 || img.Height() < 16) {
 		if img.HasAlpha() {
 			po.Format = imagetype.PNG
@@ -401,51 +532,12 @@ func ProcessImage(ctx context.Context, imgdata imagedata.ImageData, po *options.
 		)
 	}
 
-	var (
-		outData imagedata.ImageData
-		err     error
-	)
-
+	// If we want and can fit the image into the specified number of bytes,
+	// let's do it.
 	if po.MaxBytes > 0 && po.Format.SupportsQuality() {
-		outData, err = saveImageToFitBytes(ctx, po, img)
-	} else {
-		outData, err = img.Save(po.Format, po.GetQuality())
+		return saveImageToFitBytes(ctx, po, img)
 	}
 
-	if err != nil {
-		return nil, err
-	}
-
-	resultWidth, resultHeight := getImageSize(img)
-
-	return &Result{
-		OutData:      outData,
-		OriginWidth:  originWidth,
-		OriginHeight: originHeight,
-		ResultWidth:  resultWidth,
-		ResultHeight: resultHeight,
-	}, nil
-}
-
-// Returns true if image should not be processed as usual
-func shouldSkipStandardProcessing(inFormat imagetype.Type, po *options.ProcessingOptions) bool {
-	outFormat := po.Format
-	skipProcessingInFormatEnabled := slices.Contains(po.SkipProcessingFormats, inFormat)
-
-	if inFormat == imagetype.SVG {
-		isOutUnknown := outFormat == imagetype.Unknown
-
-		switch {
-		case outFormat == imagetype.SVG:
-			return true
-		case isOutUnknown && !config.AlwaysRasterizeSvg:
-			return true
-		case isOutUnknown && config.AlwaysRasterizeSvg && skipProcessingInFormatEnabled:
-			return true
-		default:
-			return false
-		}
-	} else {
-		return skipProcessingInFormatEnabled && (inFormat == outFormat || outFormat == imagetype.Unknown)
-	}
+	// Otherwise, just save the image with the specified quality.
+	return img.Save(po.Format, po.GetQuality())
 }

+ 74 - 0
processing/save_fit_bytes.go

@@ -0,0 +1,74 @@
+package processing
+
+import (
+	"context"
+
+	"github.com/imgproxy/imgproxy/v3/imagedata"
+	"github.com/imgproxy/imgproxy/v3/imath"
+	"github.com/imgproxy/imgproxy/v3/options"
+	"github.com/imgproxy/imgproxy/v3/server"
+	"github.com/imgproxy/imgproxy/v3/vips"
+)
+
+// saveImageToFitBytes tries to save the image to fit into the specified max bytes
+// by lowering the quality. It returns the image data that fits the requirement
+// or the best effort data if it was not possible to fit into the limit.
+func saveImageToFitBytes(
+	ctx context.Context,
+	po *options.ProcessingOptions,
+	img *vips.Image,
+) (imagedata.ImageData, error) {
+	var newQuality int
+
+	// Start with the quality specified in the options.
+	quality := po.GetQuality()
+
+	// We will probably save the image multiple times, so we need to process its pixels
+	// to ensure that it is in random access mode.
+	if err := img.CopyMemory(); err != nil {
+		return nil, err
+	}
+
+	for {
+		// Check for timeout or cancellation before each attempt as we might spend too much
+		// time processing the image or making previous attempts.
+		if err := server.CheckTimeout(ctx); err != nil {
+			return nil, err
+		}
+
+		imgdata, err := img.Save(po.Format, quality)
+		if err != nil {
+			return nil, err
+		}
+
+		size, err := imgdata.Size()
+		if err != nil {
+			imgdata.Close()
+			return nil, err
+		}
+
+		// If we fit the limit or quality is too low, return the result.
+		if size <= po.MaxBytes || quality <= 10 {
+			return imgdata, err
+		}
+
+		// We don't need the image data anymore, close it to free resources.
+		imgdata.Close()
+
+		// Tune quality for the next attempt based on how much we exceed the limit.
+		delta := float64(size) / float64(po.MaxBytes)
+		switch {
+		case delta > 3:
+			newQuality = imath.Scale(quality, 0.25)
+		case delta > 1.5:
+			newQuality = imath.Scale(quality, 0.5)
+		default:
+			newQuality = imath.Scale(quality, 0.75)
+		}
+
+		// Ensure that quality is always lowered, even if the scaling
+		// doesn't change it due to rounding.
+		// Also, ensure that quality doesn't go below the minimum.
+		quality = max(1, min(quality-1, newQuality))
+	}
+}

+ 15 - 1
vips/vips.c

@@ -317,7 +317,7 @@ vips_band_format(VipsImage *in)
 }
 
 gboolean
-vips_is_animated(VipsImage *in)
+vips_image_is_animated(VipsImage *in)
 {
   int n_pages;
 
@@ -329,6 +329,20 @@ vips_is_animated(VipsImage *in)
       n_pages > 1);
 }
 
+int
+vips_image_remove_animation(VipsImage *in, VipsImage **out)
+{
+  if (vips_copy(in, out, NULL))
+    return -1;
+
+  vips_image_remove(*out, "delay");
+  vips_image_remove(*out, "loop");
+  vips_image_remove(*out, "page-height");
+  vips_image_remove(*out, "n-pages");
+
+  return 0;
+}
+
 int
 vips_image_get_array_int_go(VipsImage *image, const char *name, int **out, int *n)
 {

+ 25 - 1
vips/vips.go

@@ -348,6 +348,10 @@ func (img *Image) PageHeight() int {
 	return int(C.vips_image_get_page_height(img.VipsImage))
 }
 
+// Pages returns number of pages in the image file.
+//
+// WARNING: It's not the number of pages in the loaded image.
+// Use [Image.PagesLoaded] for that.
 func (img *Image) Pages() int {
 	p, err := img.GetIntDefault("n-pages", 1)
 	if err != nil {
@@ -356,6 +360,11 @@ func (img *Image) Pages() int {
 	return p
 }
 
+// PagesLoaded returns number of pages in the loaded image.
+func (img *Image) PagesLoaded() int {
+	return img.Height() / img.PageHeight()
+}
+
 func (img *Image) Load(imgdata imagedata.ImageData, shrink int, scale float64, pages int) error {
 	var tmp *C.VipsImage
 
@@ -515,7 +524,22 @@ func (img *Image) Swap(in *Image) {
 }
 
 func (img *Image) IsAnimated() bool {
-	return C.vips_is_animated(img.VipsImage) > 0
+	return C.vips_image_is_animated(img.VipsImage) > 0
+}
+
+// RemoveAnimation removes all animation-related data from the image
+// making it a static image.
+//
+// It doesn't remove already loaded frames and keeps them vertically stacked.
+func (img *Image) RemoveAnimation() error {
+	var tmp *C.VipsImage
+
+	if C.vips_image_remove_animation(img.VipsImage, &tmp) != 0 {
+		return Error()
+	}
+
+	C.swap_and_clear(&img.VipsImage, tmp)
+	return nil
 }
 
 func (img *Image) HasAlpha() bool {

+ 2 - 1
vips/vips.h

@@ -44,7 +44,8 @@ int vips_get_orientation(VipsImage *image);
 
 VipsBandFormat vips_band_format(VipsImage *in);
 
-gboolean vips_is_animated(VipsImage *in);
+gboolean vips_image_is_animated(VipsImage *in);
+int vips_image_remove_animation(VipsImage *in, VipsImage **out);
 
 int vips_image_get_array_int_go(VipsImage *image, const char *name, int **out, int *n);
 void vips_image_set_array_int_go(VipsImage *image, const char *name, const int *array, int n);