1
0
mirror of https://github.com/imgproxy/imgproxy.git synced 2025-12-23 22:11:10 +02:00
Files
imgproxy/processing/processing.go

533 lines
15 KiB
Go
Raw Permalink Normal View History

2021-04-26 17:52:50 +06:00
package processing
import (
"context"
2025-09-15 02:15:44 +03:00
"fmt"
"log/slog"
2021-04-26 17:52:50 +06:00
"runtime"
"slices"
2021-04-26 17:52:50 +06:00
2021-09-30 20:23:30 +06:00
"github.com/imgproxy/imgproxy/v3/imagedata"
"github.com/imgproxy/imgproxy/v3/imagetype"
"github.com/imgproxy/imgproxy/v3/options"
"github.com/imgproxy/imgproxy/v3/server"
2021-09-30 20:23:30 +06:00
"github.com/imgproxy/imgproxy/v3/vips"
2021-04-26 17:52:50 +06:00
)
// mainPipeline constructs the main image processing pipeline.
// This pipeline is applied to each image frame.
func (p *Processor) mainPipeline() Pipeline {
return Pipeline{
p.vectorGuardScale,
p.trim,
p.scaleOnLoad,
p.colorspaceToProcessing,
p.crop,
p.scale,
p.rotateAndFlip,
p.cropToResult,
p.applyFilters,
p.extend,
p.extendAspectRatio,
p.padding,
p.fixSize,
p.flatten,
p.watermark,
2022-07-18 17:49:04 +06:00
}
}
2022-07-18 17:49:04 +06:00
// finalizePipeline constructs the finalization pipeline.
// This pipeline is applied before saving the image.
func (p *Processor) finalizePipeline() Pipeline {
return Pipeline{
p.colorspaceToResult,
p.stripMetadata,
2025-09-01 18:42:22 +03:00
}
2022-07-18 17:49:04 +06:00
}
2025-09-01 18:42:22 +03:00
// 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 (p *Processor) ProcessImage(
2025-09-01 18:42:22 +03:00
ctx context.Context,
imgdata imagedata.ImageData,
2025-09-23 20:16:36 +03:00
o *options.Options,
2025-09-01 18:42:22 +03:00
) (*Result, error) {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
defer vips.Cleanup()
img := new(vips.Image)
defer img.Clear()
2025-09-23 20:16:36 +03:00
po := p.NewProcessingOptions(o)
2025-09-01 18:42:22 +03:00
// Load a single page/frame of the image so we can analyze it
// and decide how to process it further
2025-09-23 20:16:36 +03:00
thumbnailLoaded, err := p.initialLoadImage(img, imgdata, po.EnforceThumbnail())
2025-09-01 18:42:22 +03:00
if err != nil {
return nil, err
}
// Let's check if we should skip standard processing
if p.shouldSkipStandardProcessing(imgdata.Format(), po) {
return p.skipStandardProcessing(img, imgdata, po)
2025-09-01 18:42:22 +03:00
}
// 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.MaxAnimationFrames() > 1 && img.IsAnimated()
2022-07-18 17:49:04 +06:00
2025-09-01 18:42:22 +03:00
// Determine output format and check if it's supported.
2025-09-23 20:16:36 +03:00
// The determined format is stored in po[KeyFormat].
outFormat, err := p.determineOutputFormat(img, imgdata, po, animated)
if err != nil {
2025-09-01 18:42:22 +03:00
return nil, err
}
// Now, as we know the output format, we know for sure if the image
// should be processed as animated
2025-09-23 20:16:36 +03:00
animated = animated && outFormat.SupportsAnimationSave()
2025-09-01 18:42:22 +03:00
// 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 = p.reloadImageForProcessing(img, imgdata, po, animated); err != nil {
2025-09-01 18:42:22 +03:00
return nil, err
2022-07-18 17:49:04 +06:00
}
2025-09-01 18:42:22 +03:00
}
2022-07-18 17:49:04 +06:00
2025-09-01 18:42:22 +03:00
// Check image dimensions and number of frames for security reasons
originWidth, originHeight, err := p.checkImageSize(img, imgdata.Format(), po)
2025-09-01 18:42:22 +03:00
if err != nil {
return nil, err
2022-07-18 17:49:04 +06:00
}
2025-09-01 18:42:22 +03:00
// Transform the image (resize, crop, etc)
if err = p.transformImage(ctx, img, po, imgdata, animated); err != nil {
2025-09-01 18:42:22 +03:00
return nil, err
}
2022-07-18 17:49:04 +06:00
2025-09-01 18:42:22 +03:00
// Finalize the image (colorspace conversion, metadata stripping, etc)
if err = p.finalizePipeline().Run(ctx, img, po, imgdata); err != nil {
2025-09-01 18:42:22 +03:00
return nil, err
}
2022-07-18 19:45:01 +06:00
outData, err := p.saveImage(ctx, img, po)
2025-09-01 18:42:22 +03:00
if err != nil {
return nil, err
}
resultWidth, resultHeight, _ := p.getImageSize(img)
2025-09-01 18:42:22 +03:00
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 (p *Processor) initialLoadImage(
2025-09-01 18:42:22 +03:00
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
2022-07-18 19:45:01 +06:00
} else {
2025-09-15 02:15:44 +03:00
slog.Debug(fmt.Sprintf("Can't load thumbnail: %s", err))
2022-07-18 17:49:04 +06:00
}
}
return false, img.Load(imgdata, 1.0, 0, 1)
2025-09-01 18:42:22 +03:00
}
// reloadImageForProcessing reloads the image for processing.
// For animated images, it loads all frames up to MaxAnimationFrames.
func (p *Processor) reloadImageForProcessing(
2025-09-01 18:42:22 +03:00
img *vips.Image,
imgdata imagedata.ImageData,
2025-09-23 20:16:36 +03:00
po ProcessingOptions,
2025-09-01 18:42:22 +03:00
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.MaxAnimationFrames())
return img.Load(imgdata, 1.0, 0, frames)
2022-07-18 19:45:01 +06:00
}
2025-09-01 18:42:22 +03:00
// Otherwise, we just need to remove any animation-related data
return img.RemoveAnimation()
}
2022-07-18 19:45:01 +06:00
2025-09-01 18:42:22 +03:00
// 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 (p *Processor) checkImageSize(
2025-09-01 18:42:22 +03:00
img *vips.Image,
imgtype imagetype.Type,
po ProcessingOptions,
2025-09-01 18:42:22 +03:00
) (int, int, error) {
width, height, frames := p.getImageSize(img)
2025-09-01 18:42:22 +03:00
if imgtype.IsVector() {
// We don't check vector image dimensions as we can render it in any size
return width, height, nil
}
err := p.securityChecker.CheckDimensions(po.Options, width, height, frames)
2025-09-01 18:42:22 +03:00
return width, height, err
2021-04-26 17:52:50 +06:00
}
2025-09-01 18:42:22 +03:00
// getImageSize returns the width and height of the image, taking into account
// orientation and animation.
func (p *Processor) getImageSize(img *vips.Image) (int, int, int) {
2025-08-16 18:06:16 +03:00
width, height := img.Width(), img.Height()
2025-09-01 18:42:22 +03:00
frames := 1
2025-08-16 18:06:16 +03:00
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()
2025-09-01 18:42:22 +03:00
frames = img.PagesLoaded()
2025-08-16 18:06:16 +03:00
}
// If the image is rotated by 90 or 270 degrees, we need to swap width and height
orientation := img.Orientation()
if orientation == 5 || orientation == 6 || orientation == 7 || orientation == 8 {
width, height = height, width
}
2025-09-01 18:42:22 +03:00
return width, height, frames
}
2025-09-01 18:42:22 +03:00
// Returns true if image should not be processed as usual
func (p *Processor) shouldSkipStandardProcessing(
inFormat imagetype.Type,
2025-09-23 20:16:36 +03:00
po ProcessingOptions,
) bool {
2025-09-23 20:16:36 +03:00
outFormat := po.Format()
skipProcessingFormatEnabled := po.ShouldSkipFormatProcessing(inFormat)
2021-04-26 17:52:50 +06:00
2025-09-01 18:42:22 +03:00
if inFormat == imagetype.SVG {
isOutUnknown := outFormat == imagetype.Unknown
2021-04-26 17:52:50 +06:00
2025-09-01 18:42:22 +03:00
switch {
case outFormat == imagetype.SVG:
return true
case isOutUnknown && !p.config.AlwaysRasterizeSvg:
2025-09-01 18:42:22 +03:00
return true
case isOutUnknown && p.config.AlwaysRasterizeSvg && skipProcessingFormatEnabled:
2025-09-01 18:42:22 +03:00
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 (p *Processor) skipStandardProcessing(
2025-09-01 18:42:22 +03:00
img *vips.Image,
imgdata imagedata.ImageData,
2025-09-23 20:16:36 +03:00
po ProcessingOptions,
2025-09-01 18:42:22 +03:00
) (*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 := p.checkImageSize(img, imgdata.Format(), po)
2021-04-26 17:52:50 +06:00
if err != nil {
2025-09-01 18:42:22 +03:00
return nil, err
2021-04-26 17:52:50 +06:00
}
2025-10-03 16:48:37 +02:00
imgdata, err = p.svg.Process(po.Options, imgdata)
if err != nil {
return nil, err
2021-04-26 17:52:50 +06:00
}
2025-09-01 18:42:22 +03:00
// 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 (p *Processor) determineOutputFormat(
2025-09-01 18:42:22 +03:00
img *vips.Image,
imgdata imagedata.ImageData,
2025-09-23 20:16:36 +03:00
po ProcessingOptions,
2025-09-01 18:42:22 +03:00
animated bool,
2025-09-23 20:16:36 +03:00
) (imagetype.Type, error) {
2025-09-01 18:42:22 +03:00
// Check if the image may have transparency
2025-09-23 20:16:36 +03:00
expectTransparency := !po.ShouldFlatten() &&
(img.HasAlpha() || po.PaddingEnabled() || po.ExtendEnabled())
format := po.Format()
2025-09-01 18:42:22 +03:00
switch {
2025-09-23 20:16:36 +03:00
case format == imagetype.SVG:
2025-09-01 18:42:22 +03:00
// At this point we can't allow requested format to be SVG as we can't save SVGs
2025-09-23 20:16:36 +03:00
return imagetype.Unknown, newSaveFormatError(format)
case format == imagetype.Unknown:
2025-09-01 18:42:22 +03:00
switch {
2025-09-23 20:16:36 +03:00
case po.PreferJxl() && !animated:
format = imagetype.JXL
case po.PreferAvif() && !animated:
format = imagetype.AVIF
case po.PreferWebP():
format = imagetype.WEBP
case p.isImageTypePreferred(imgdata.Format()):
2025-09-23 20:16:36 +03:00
format = imgdata.Format()
2025-09-01 18:42:22 +03:00
default:
2025-09-23 20:16:36 +03:00
format = p.findPreferredFormat(animated, expectTransparency)
2025-09-01 18:42:22 +03:00
}
2025-09-23 20:16:36 +03:00
case po.EnforceJxl() && !animated:
format = imagetype.JXL
case po.EnforceAvif() && !animated:
format = imagetype.AVIF
case po.EnforceWebP():
format = imagetype.WEBP
2025-09-01 18:42:22 +03:00
}
2025-09-23 20:16:36 +03:00
po.SetFormat(format)
if !vips.SupportsSave(format) {
return format, newSaveFormatError(format)
2025-09-01 18:42:22 +03:00
}
2025-09-23 20:16:36 +03:00
return format, nil
2025-09-01 18:42:22 +03:00
}
// isImageTypePreferred checks if the given image type is in the list of preferred formats.
func (p *Processor) isImageTypePreferred(imgtype imagetype.Type) bool {
return slices.Contains(p.config.PreferredFormats, imgtype)
2025-09-01 18:42:22 +03:00
}
// isImageTypeCompatible checks if the given image type is compatible with the image properties.
func (p *Processor) isImageTypeCompatible(
imgtype imagetype.Type,
animated, expectTransparency bool,
) bool {
2025-09-01 18:42:22 +03:00
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 (p *Processor) findPreferredFormat(animated, expectTransparency bool) imagetype.Type {
for _, t := range p.config.PreferredFormats {
if p.isImageTypeCompatible(t, animated, expectTransparency) {
2025-09-01 18:42:22 +03:00
return t
2021-04-26 17:52:50 +06:00
}
}
return p.config.PreferredFormats[0]
2025-09-01 18:42:22 +03:00
}
func (p *Processor) transformImage(
2025-09-01 18:42:22 +03:00
ctx context.Context,
img *vips.Image,
2025-09-23 20:16:36 +03:00
po ProcessingOptions,
2025-09-01 18:42:22 +03:00
imgdata imagedata.ImageData,
asAnimated bool,
) error {
if asAnimated {
return p.transformAnimated(ctx, img, po)
2025-09-01 18:42:22 +03:00
}
return p.mainPipeline().Run(ctx, img, po, imgdata)
2025-09-01 18:42:22 +03:00
}
func (p *Processor) transformAnimated(
2025-09-01 18:42:22 +03:00
ctx context.Context,
img *vips.Image,
2025-09-23 20:16:36 +03:00
po ProcessingOptions,
2025-09-01 18:42:22 +03:00
) error {
2025-09-23 20:16:36 +03:00
if po.TrimEnabled() {
2025-09-15 02:15:44 +03:00
slog.Warn("Trim is not supported for animated images")
2025-09-23 20:16:36 +03:00
po.DisableTrim()
2025-09-01 18:42:22 +03:00
}
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.
2021-04-26 17:52:50 +06:00
delay, err := img.GetIntSliceDefault("delay", nil)
if err != nil {
return err
}
2025-09-01 18:42:22 +03:00
// Get loop count. We'll need to set it back later.
// 0 means infinite looping.
2021-04-26 17:52:50 +06:00
loop, err := img.GetIntDefault("loop", 0)
if err != nil {
return err
}
2025-09-01 18:42:22 +03:00
// Disable watermarking for individual frames.
// It's more efficient to apply watermark to all frames at once after they are processed.
2025-09-23 20:16:36 +03:00
watermarkOpacity := po.WatermarkOpacity()
if watermarkOpacity > 0 {
po.DeleteWatermarkOpacity()
defer func() { po.SetWatermarkOpacity(watermarkOpacity) }()
}
2021-04-26 17:52:50 +06:00
2025-09-01 18:42:22 +03:00
// Make a slice to hold processed frames and ensure they are cleared on function exit
2022-06-10 15:27:15 +06:00
frames := make([]*vips.Image, 0, framesCount)
2021-04-26 17:52:50 +06:00
defer func() {
for _, frame := range frames {
if frame != nil {
frame.Clear()
}
}
}()
for i := range framesCount {
2021-04-26 17:52:50 +06:00
frame := new(vips.Image)
2025-09-01 18:42:22 +03:00
// Extract an individual frame from the image.
// Libvips loads animated images as a single image with frames stacked vertically.
2021-04-26 17:52:50 +06:00
if err = img.Extract(frame, 0, i*frameHeight, imgWidth, frameHeight); err != nil {
return err
}
2022-06-10 15:27:15 +06:00
frames = append(frames, frame)
2021-04-26 17:52:50 +06:00
2025-09-01 18:42:22 +03:00
// Transform the frame using the main pipeline.
// We don't provide imgdata here to prevent scale-on-load.
2025-09-18 10:29:42 +02:00
// Watermarking is disabled for individual frames (see above)
if err = p.mainPipeline().Run(ctx, frame, po, nil); err != nil {
2021-04-26 17:52:50 +06:00
return err
}
2025-09-01 18:42:22 +03:00
// 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
}
if err = server.CheckTimeout(ctx); err != nil {
return err
}
}
2021-04-26 17:52:50 +06:00
}
2025-09-01 18:42:22 +03:00
// Join processed frames back into a single image.
2021-04-26 17:52:50 +06:00
if err = img.Arrayjoin(frames); err != nil {
return err
}
2025-09-01 18:42:22 +03:00
// Apply watermark to all frames at once if it was requested.
// This is much more efficient than applying watermark to individual frames.
2025-09-23 20:16:36 +03:00
if watermarkOpacity > 0 && p.watermarkProvider != nil {
2025-09-01 18:42:22 +03:00
// 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
}
2025-09-23 20:16:36 +03:00
// Set watermark opacity back
po.SetWatermarkOpacity(watermarkOpacity)
if err = p.applyWatermark(ctx, img, po, dprScale, framesCount); err != nil {
2021-04-26 17:52:50 +06:00
return err
}
}
if len(delay) == 0 {
2025-09-01 18:42:22 +03:00
// if we don't have delay info, set it to 40ms for each frame (25 FPS).
2021-04-26 17:52:50 +06:00
delay = make([]int, framesCount)
for i := range delay {
delay[i] = 40
}
} else if len(delay) > framesCount {
2025-09-01 18:42:22 +03:00
// if we have more delay entries than frames, truncate it.
2021-04-26 17:52:50 +06:00
delay = delay[:framesCount]
}
2025-09-01 18:42:22 +03:00
// Mark the image as animated so img.Strip() doesn't remove animation data.
img.SetInt("imgproxy-is-animated", 1)
2025-09-01 18:42:22 +03:00
// Set animation data back.
2021-04-26 17:52:50 +06:00
img.SetInt("page-height", frames[0].Height())
img.SetIntSlice("delay", delay)
img.SetInt("loop", loop)
img.SetInt("n-pages", img.Height()/frames[0].Height())
2021-04-26 17:52:50 +06:00
return nil
}
func (p *Processor) saveImage(
2025-09-01 18:42:22 +03:00
ctx context.Context,
img *vips.Image,
2025-09-23 20:16:36 +03:00
po ProcessingOptions,
2025-09-01 18:42:22 +03:00
) (imagedata.ImageData, error) {
2025-09-23 20:16:36 +03:00
outFormat := po.Format()
2025-09-01 18:42:22 +03:00
// AVIF has a minimal dimension of 16 pixels.
// If one of the dimensions is less, we need to switch to another format.
2025-09-23 20:16:36 +03:00
if outFormat == imagetype.AVIF && (img.Width() < 16 || img.Height() < 16) {
if img.HasAlpha() {
2025-09-23 20:16:36 +03:00
outFormat = imagetype.PNG
} else {
2025-09-23 20:16:36 +03:00
outFormat = imagetype.JPEG
}
2025-09-23 20:16:36 +03:00
po.SetFormat(outFormat)
2025-09-15 02:15:44 +03:00
slog.Warn(fmt.Sprintf(
2022-05-20 22:33:21 +06:00
"Minimal dimension of AVIF is 16, current image size is %dx%d. Image will be saved as %s",
2025-09-23 20:16:36 +03:00
img.Width(), img.Height(), outFormat,
2025-09-15 02:15:44 +03:00
))
}
2025-09-23 20:16:36 +03:00
quality := po.Quality(outFormat)
2025-09-01 18:42:22 +03:00
// If we want and can fit the image into the specified number of bytes,
// let's do it.
2025-09-23 20:16:36 +03:00
if maxBytes := po.MaxBytes(); maxBytes > 0 && outFormat.SupportsQuality() {
2025-09-26 16:41:59 +03:00
return saveImageToFitBytes(ctx, img, outFormat, quality, maxBytes, po.Options)
}
2025-09-01 18:42:22 +03:00
// Otherwise, just save the image with the specified quality.
2025-09-26 16:41:59 +03:00
return img.Save(outFormat, quality, po.Options)
}