• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

cshum / imagor / 21755680381

06 Feb 2026 03:19PM UTC coverage: 91.916% (+0.04%) from 91.874%
21755680381

push

github

web-flow
feat: (adaptive-)(full-)fit-in  (#732)

* fix

* test: reset golden

* test: update golden files

* feat: (adaptive-)(full-)fit-in (#731)

* test: reset golden

* test: update golden files

---------

Co-authored-by: cshum <293790+cshum@users.noreply.github.com>

13 of 13 new or added lines in 1 file covered. (100.0%)

1 existing line in 1 file now uncovered.

5765 of 6272 relevant lines covered (91.92%)

1.1 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

88.26
/processor/vipsprocessor/process.go
1
package vipsprocessor
2

3
import (
4
        "context"
5
        "math"
6
        "strconv"
7
        "strings"
8
        "time"
9

10
        "github.com/cshum/imagor"
11
        "github.com/cshum/imagor/imagorpath"
12
        "github.com/cshum/vipsgen/vips"
13
        "go.uber.org/zap"
14
)
15

16
var imageTypeMap = map[string]vips.ImageType{
17
        "gif":  vips.ImageTypeGif,
18
        "jpeg": vips.ImageTypeJpeg,
19
        "jpg":  vips.ImageTypeJpeg,
20
        "pdf":  vips.ImageTypePdf,
21
        "png":  vips.ImageTypePng,
22
        "svg":  vips.ImageTypeSvg,
23
        "tiff": vips.ImageTypeTiff,
24
        "webp": vips.ImageTypeWebp,
25
        "heif": vips.ImageTypeHeif,
26
        "bmp":  vips.ImageTypeBmp,
27
        "avif": vips.ImageTypeAvif,
28
        "jp2":  vips.ImageTypeJp2k,
29
        "jxl":  vips.ImageTypeJxl,
30
}
31

32
// IsAnimationSupported indicates if image type supports animation
33
func IsAnimationSupported(imageType vips.ImageType) bool {
1✔
34
        return imageType == vips.ImageTypeGif || imageType == vips.ImageTypeWebp
1✔
35
}
1✔
36

37
// exportParams holds parameters needed for image export
38
type exportParams struct {
39
        format        vips.ImageType
40
        quality       int
41
        compression   int
42
        bitdepth      int
43
        palette       bool
44
        stripMetadata bool
45
        maxBytes      int
46
}
47

48
// Process implements imagor.Processor interface
49
func (v *Processor) Process(
50
        ctx context.Context, blob *imagor.Blob, p imagorpath.Params, load imagor.LoadFunc,
51
) (*imagor.Blob, error) {
1✔
52
        ctx = withContext(ctx)
1✔
53
        defer contextDone(ctx)
1✔
54

1✔
55
        // Load and process the image
1✔
56
        img, err := v.loadAndProcess(ctx, blob, p, load)
1✔
57
        if err != nil {
2✔
58
                return nil, err
1✔
59
        }
1✔
60
        defer img.Close()
1✔
61

1✔
62
        // Extract export parameters
1✔
63
        params := v.extractExportParams(p, blob, img)
1✔
64

1✔
65
        // Handle metadata response
1✔
66
        if p.Meta {
2✔
67
                stripExif := false
1✔
68
                for _, f := range p.Filters {
2✔
69
                        if f.Name == "strip_exif" {
2✔
70
                                stripExif = true
1✔
71
                                break
1✔
72
                        }
73
                }
74
                return imagor.NewBlobFromJsonMarshal(metadata(img, params.format, stripExif)), nil
1✔
75
        }
76

77
        // Export with max_bytes retry loop
78
        params.format = supportedSaveFormat(params.format)
1✔
79
        for {
2✔
80
                buf, err := v.export(img, params.format, params.compression, params.quality, params.palette, params.bitdepth, params.stripMetadata)
1✔
81
                if err != nil {
1✔
82
                        return nil, WrapErr(err)
×
83
                }
×
84
                if params.maxBytes > 0 && (params.quality > 10 || params.quality == 0) && params.format != vips.ImageTypePng {
2✔
85
                        ln := len(buf)
1✔
86
                        if v.Debug {
2✔
87
                                v.Logger.Debug("max_bytes",
1✔
88
                                        zap.Int("bytes", ln),
1✔
89
                                        zap.Int("quality", params.quality),
1✔
90
                                )
1✔
91
                        }
1✔
92
                        if ln > params.maxBytes {
2✔
93
                                if params.quality == 0 {
2✔
94
                                        params.quality = 80
1✔
95
                                }
1✔
96
                                delta := float64(ln) / float64(params.maxBytes)
1✔
97
                                switch {
1✔
98
                                case delta > 3:
1✔
99
                                        params.quality = params.quality * 25 / 100
1✔
100
                                case delta > 1.5:
1✔
101
                                        params.quality = params.quality * 50 / 100
1✔
102
                                default:
×
103
                                        params.quality = params.quality * 75 / 100
×
104
                                }
105
                                if err := ctx.Err(); err != nil {
1✔
106
                                        return nil, WrapErr(err)
×
107
                                }
×
108
                                continue
1✔
109
                        }
110
                }
111
                blob := imagor.NewBlobFromBytes(buf)
1✔
112
                if typ, ok := params.format.MimeType(); ok {
2✔
113
                        blob.SetContentType(typ)
1✔
114
                }
1✔
115
                return blob, nil
1✔
116
        }
117
}
118

119
// extractExportParams extracts export-related parameters from filters
120
func (v *Processor) extractExportParams(p imagorpath.Params, blob *imagor.Blob, img *vips.Image) *exportParams {
1✔
121
        var (
1✔
122
                quality       int
1✔
123
                bitdepth      int
1✔
124
                compression   int
1✔
125
                palette       bool
1✔
126
                stripMetadata = v.StripMetadata
1✔
127
                maxBytes      int
1✔
128
                format        = vips.ImageTypeUnknown
1✔
129
        )
1✔
130

1✔
131
        // Extract export parameters from filters
1✔
132
        for _, f := range p.Filters {
2✔
133
                if v.disableFilters[f.Name] {
2✔
134
                        continue
1✔
135
                }
136
                switch f.Name {
1✔
137
                case "format":
1✔
138
                        if imageType, ok := imageTypeMap[f.Args]; ok {
2✔
139
                                format = supportedSaveFormat(imageType)
1✔
140
                        }
1✔
141
                case "quality":
1✔
142
                        quality, _ = strconv.Atoi(f.Args)
1✔
143
                case "autojpg":
1✔
144
                        format = vips.ImageTypeJpeg
1✔
145
                case "palette":
1✔
146
                        palette = true
1✔
147
                case "bitdepth":
1✔
148
                        bitdepth, _ = strconv.Atoi(f.Args)
1✔
149
                case "compression":
1✔
150
                        compression, _ = strconv.Atoi(f.Args)
1✔
151
                case "max_bytes":
1✔
152
                        if n, _ := strconv.Atoi(f.Args); n > 0 {
2✔
153
                                maxBytes = n
1✔
154
                        }
1✔
155
                case "strip_metadata":
1✔
156
                        stripMetadata = true
1✔
157
                }
158
        }
159

160
        // Determine format if not specified
161
        if format == vips.ImageTypeUnknown {
2✔
162
                if blob.BlobType() == imagor.BlobTypeAVIF {
2✔
163
                        format = vips.ImageTypeAvif
1✔
164
                } else {
2✔
165
                        format = img.Format()
1✔
166
                }
1✔
167
        }
168

169
        return &exportParams{
1✔
170
                format:        format,
1✔
171
                quality:       quality,
1✔
172
                compression:   compression,
1✔
173
                bitdepth:      bitdepth,
1✔
174
                palette:       palette,
1✔
175
                stripMetadata: stripMetadata,
1✔
176
                maxBytes:      maxBytes,
1✔
177
        }
1✔
178
}
179

180
// loadAndProcess loads the image from blob and applies all transformations
181
func (v *Processor) loadAndProcess(
182
        ctx context.Context, blob *imagor.Blob, p imagorpath.Params, load imagor.LoadFunc,
183
) (*vips.Image, error) {
1✔
184
        var (
1✔
185
                thumbnailNotSupported bool
1✔
186
                upscale               = true
1✔
187
                stretch               = p.Stretch
1✔
188
                thumbnail             = false
1✔
189
                orient                int
1✔
190
                img                   *vips.Image
1✔
191
                maxN                  = v.MaxAnimationFrames
1✔
192
                page                  = 1
1✔
193
                dpi                   = 0
1✔
194
                err                   error
1✔
195
        )
1✔
196
        if p.Trim || p.VFlip || p.FullFitIn || p.AdaptiveFitIn {
2✔
197
                thumbnailNotSupported = true
1✔
198
        }
1✔
199
        if p.FitIn {
2✔
200
                upscale = false
1✔
201
        }
1✔
202
        if maxN == 0 || maxN < -1 {
2✔
203
                maxN = 1
1✔
204
        }
1✔
205
        if blob != nil && !blob.SupportsAnimation() {
2✔
206
                maxN = 1
1✔
207
        }
1✔
208
        for _, f := range p.Filters {
2✔
209
                if v.disableFilters[f.Name] {
2✔
210
                        continue
1✔
211
                }
212
                switch f.Name {
1✔
213
                case "format":
1✔
214
                        if imageType, ok := imageTypeMap[f.Args]; ok {
2✔
215
                                format := supportedSaveFormat(imageType)
1✔
216
                                if !IsAnimationSupported(format) {
2✔
217
                                        // no frames if export format not support animation
1✔
218
                                        maxN = 1
1✔
219
                                }
1✔
220
                        }
221
                case "max_frames":
1✔
222
                        if n, _ := strconv.Atoi(f.Args); n > 0 && (maxN == -1 || n < maxN) {
2✔
223
                                maxN = n
1✔
224
                        }
1✔
225
                case "stretch":
1✔
226
                        stretch = true
1✔
227
                case "upscale":
1✔
228
                        upscale = true
1✔
229
                case "no_upscale":
1✔
230
                        upscale = false
1✔
231
                case "fill", "background_color":
1✔
232
                        if args := strings.Split(f.Args, ","); args[0] == "auto" {
2✔
233
                                thumbnailNotSupported = true
1✔
234
                        }
1✔
235
                case "page":
1✔
236
                        if n, _ := strconv.Atoi(f.Args); n > 0 {
2✔
237
                                page = n
1✔
238
                        }
1✔
239
                case "dpi":
×
240
                        if n, _ := strconv.Atoi(f.Args); n > 0 {
×
241
                                dpi = n
×
242
                        }
×
243
                case "orient":
1✔
244
                        if n, _ := strconv.Atoi(f.Args); n > 0 {
2✔
245
                                orient = n
1✔
246
                                thumbnailNotSupported = true
1✔
247
                        }
1✔
248
                case "max_bytes":
1✔
249
                        if n, _ := strconv.Atoi(f.Args); n > 0 {
2✔
250
                                thumbnailNotSupported = true
1✔
251
                        }
1✔
252
                case "trim", "focal", "rotate":
1✔
253
                        thumbnailNotSupported = true
1✔
254
                }
255
        }
256

257
        if !thumbnailNotSupported &&
1✔
258
                p.CropBottom == 0.0 && p.CropTop == 0.0 && p.CropLeft == 0.0 && p.CropRight == 0.0 {
2✔
259
                // apply shrink-on-load where possible
1✔
260
                if p.FitIn {
2✔
261
                        if p.Width > 0 || p.Height > 0 {
2✔
262
                                w := p.Width
1✔
263
                                h := p.Height
1✔
264
                                if w == 0 {
2✔
265
                                        w = v.MaxWidth
1✔
266
                                }
1✔
267
                                if h == 0 {
2✔
268
                                        h = v.MaxHeight
1✔
269
                                }
1✔
270
                                size := vips.SizeDown
1✔
271
                                if upscale {
2✔
272
                                        size = vips.SizeBoth
1✔
273
                                }
1✔
274
                                if img, err = v.NewThumbnail(
1✔
275
                                        ctx, blob, w, h, vips.InterestingNone, size, maxN, page, dpi,
1✔
276
                                ); err != nil {
1✔
277
                                        return nil, err
×
278
                                }
×
279
                                thumbnail = true
1✔
280
                        }
281
                } else if stretch {
2✔
282
                        if p.Width > 0 && p.Height > 0 {
2✔
283
                                if img, err = v.NewThumbnail(
1✔
284
                                        ctx, blob, p.Width, p.Height,
1✔
285
                                        vips.InterestingNone, vips.SizeForce, maxN, page, dpi,
1✔
286
                                ); err != nil {
1✔
287
                                        return nil, err
×
288
                                }
×
289
                                thumbnail = true
1✔
290
                        }
291
                } else {
1✔
292
                        if p.Width > 0 && p.Height > 0 {
2✔
293
                                interest := vips.InterestingNone
1✔
294
                                if p.Smart {
2✔
295
                                        interest = vips.InterestingAttention
1✔
296
                                        thumbnail = true
1✔
297
                                } else if (p.VAlign == imagorpath.VAlignTop && p.HAlign == "") ||
2✔
298
                                        (p.HAlign == imagorpath.HAlignLeft && p.VAlign == "") {
2✔
299
                                        interest = vips.InterestingLow
1✔
300
                                        thumbnail = true
1✔
301
                                } else if (p.VAlign == imagorpath.VAlignBottom && p.HAlign == "") ||
2✔
302
                                        (p.HAlign == imagorpath.HAlignRight && p.VAlign == "") {
2✔
303
                                        interest = vips.InterestingHigh
1✔
304
                                        thumbnail = true
1✔
305
                                } else if (p.VAlign == "" || p.VAlign == "middle") &&
2✔
306
                                        (p.HAlign == "" || p.HAlign == "center") {
2✔
307
                                        interest = vips.InterestingCentre
1✔
308
                                        thumbnail = true
1✔
309
                                }
1✔
310
                                if thumbnail {
2✔
311
                                        if img, err = v.NewThumbnail(
1✔
312
                                                ctx, blob, p.Width, p.Height,
1✔
313
                                                interest, vips.SizeBoth, maxN, page, dpi,
1✔
314
                                        ); err != nil {
2✔
315
                                                return nil, err
1✔
316
                                        }
1✔
317
                                }
318
                        } else if p.Width > 0 && p.Height == 0 {
2✔
319
                                if img, err = v.NewThumbnail(
1✔
320
                                        ctx, blob, p.Width, v.MaxHeight,
1✔
321
                                        vips.InterestingNone, vips.SizeBoth, maxN, page, dpi,
1✔
322
                                ); err != nil {
2✔
323
                                        return nil, err
1✔
324
                                }
1✔
325
                                thumbnail = true
1✔
326
                        } else if p.Height > 0 && p.Width == 0 {
2✔
327
                                if img, err = v.NewThumbnail(
1✔
328
                                        ctx, blob, v.MaxWidth, p.Height,
1✔
329
                                        vips.InterestingNone, vips.SizeBoth, maxN, page, dpi,
1✔
330
                                ); err != nil {
1✔
331
                                        return nil, err
×
332
                                }
×
333
                                thumbnail = true
1✔
334
                        }
335
                }
336
        }
337
        if !thumbnail {
2✔
338
                if thumbnailNotSupported {
2✔
339
                        if img, err = v.NewImage(ctx, blob, maxN, page, dpi); err != nil {
1✔
340
                                return nil, err
×
341
                        }
×
342
                } else {
1✔
343
                        if img, err = v.NewThumbnail(
1✔
344
                                ctx, blob, v.MaxWidth, v.MaxHeight,
1✔
345
                                vips.InterestingNone, vips.SizeDown, maxN, page, dpi,
1✔
346
                        ); err != nil {
2✔
347
                                return nil, err
1✔
348
                        }
1✔
349
                }
350
        }
351

352
        if orient > 0 {
2✔
353
                // orient rotate before resize
1✔
354
                if err = img.RotMultiPage(getAngle(orient)); err != nil {
1✔
355
                        return nil, err
×
356
                }
×
357
        }
358

359
        var (
1✔
360
                origWidth  = float64(img.Width())
1✔
361
                origHeight = float64(img.PageHeight())
1✔
362
        )
1✔
363
        if v.Debug {
2✔
364
                v.Logger.Debug("image",
1✔
365
                        zap.Int("width", img.Width()),
1✔
366
                        zap.Int("height", img.Height()),
1✔
367
                        zap.Int("page_height", img.PageHeight()))
1✔
368
        }
1✔
369

370
        // Extract focal points for transformation
371
        var focalRects []focal
1✔
372
        for _, f := range p.Filters {
2✔
373
                if v.disableFilters[f.Name] {
2✔
374
                        continue
1✔
375
                }
376
                if f.Name == "focal" {
2✔
377
                        args := strings.FieldsFunc(f.Args, argSplit)
1✔
378
                        switch len(args) {
1✔
379
                        case 4:
1✔
380
                                rect := focal{}
1✔
381
                                rect.Left, _ = strconv.ParseFloat(args[0], 64)
1✔
382
                                rect.Top, _ = strconv.ParseFloat(args[1], 64)
1✔
383
                                rect.Right, _ = strconv.ParseFloat(args[2], 64)
1✔
384
                                rect.Bottom, _ = strconv.ParseFloat(args[3], 64)
1✔
385
                                if rect.Left < 1 && rect.Top < 1 && rect.Right <= 1 && rect.Bottom <= 1 {
2✔
386
                                        rect.Left *= origWidth
1✔
387
                                        rect.Right *= origWidth
1✔
388
                                        rect.Top *= origHeight
1✔
389
                                        rect.Bottom *= origHeight
1✔
390
                                }
1✔
391
                                if rect.Right > rect.Left && rect.Bottom > rect.Top {
2✔
392
                                        focalRects = append(focalRects, rect)
1✔
393
                                }
1✔
394
                        case 2:
1✔
395
                                rect := focal{}
1✔
396
                                rect.Left, _ = strconv.ParseFloat(args[0], 64)
1✔
397
                                rect.Top, _ = strconv.ParseFloat(args[1], 64)
1✔
398
                                if rect.Left < 1 && rect.Top < 1 {
2✔
399
                                        rect.Left *= origWidth
1✔
400
                                        rect.Top *= origHeight
1✔
401
                                }
1✔
402
                                rect.Right = rect.Left + 1
1✔
403
                                rect.Bottom = rect.Top + 1
1✔
404
                                focalRects = append(focalRects, rect)
1✔
405
                        }
406
                }
407
        }
408
        // Apply transformations
409
        if err := v.applyTransformations(ctx, img, p, load, thumbnail, stretch, upscale, focalRects); err != nil {
1✔
410
                return nil, WrapErr(err)
×
411
        }
×
412

413
        return img, nil
1✔
414
}
415

416
// applyTransformations applies all image transformations (crop, resize, flip, filters)
417
func (v *Processor) applyTransformations(
418
        ctx context.Context, img *vips.Image, p imagorpath.Params, load imagor.LoadFunc, thumbnail, stretch, upscale bool, focalRects []focal,
419
) error {
1✔
420
        var (
1✔
421
                origWidth  = float64(img.Width())
1✔
422
                origHeight = float64(img.PageHeight())
1✔
423
                cropLeft,
1✔
424
                cropTop,
1✔
425
                cropRight,
1✔
426
                cropBottom float64
1✔
427
        )
1✔
428
        if p.CropRight > 0 || p.CropLeft > 0 || p.CropBottom > 0 || p.CropTop > 0 {
2✔
429
                // percentage
1✔
430
                cropLeft = math.Max(p.CropLeft, 0)
1✔
431
                cropTop = math.Max(p.CropTop, 0)
1✔
432
                cropRight = p.CropRight
1✔
433
                cropBottom = p.CropBottom
1✔
434
                if p.CropLeft < 1 && p.CropTop < 1 && p.CropRight <= 1 && p.CropBottom <= 1 {
2✔
435
                        cropLeft = math.Round(cropLeft * origWidth)
1✔
436
                        cropTop = math.Round(cropTop * origHeight)
1✔
437
                        cropRight = math.Round(cropRight * origWidth)
1✔
438
                        cropBottom = math.Round(cropBottom * origHeight)
1✔
439
                }
1✔
440
                if cropRight == 0 {
2✔
441
                        cropRight = origWidth - 1
1✔
442
                }
1✔
443
                if cropBottom == 0 {
2✔
444
                        cropBottom = origHeight - 1
1✔
445
                }
1✔
446
                cropRight = math.Min(cropRight, origWidth-1)
1✔
447
                cropBottom = math.Min(cropBottom, origHeight-1)
1✔
448
        }
449
        if p.Trim {
2✔
450
                if l, t, w, h, err := findTrim(ctx, img, p.TrimBy, p.TrimTolerance); err == nil {
2✔
451
                        cropLeft = math.Max(cropLeft, float64(l))
1✔
452
                        cropTop = math.Max(cropTop, float64(t))
1✔
453
                        if cropRight > 0 {
2✔
454
                                cropRight = math.Min(cropRight, float64(l+w))
1✔
455
                        } else {
2✔
456
                                cropRight = float64(l + w)
1✔
457
                        }
1✔
458
                        if cropBottom > 0 {
2✔
459
                                cropBottom = math.Min(cropBottom, float64(t+h))
1✔
460
                        } else {
2✔
461
                                cropBottom = float64(t + h)
1✔
462
                        }
1✔
463
                }
464
        }
465
        if cropRight > cropLeft && cropBottom > cropTop {
2✔
466
                if err := img.ExtractAreaMultiPage(
1✔
467
                        int(cropLeft), int(cropTop), int(cropRight-cropLeft), int(cropBottom-cropTop),
1✔
468
                ); err != nil {
1✔
469
                        return err
×
470
                }
×
471
        }
472
        var (
1✔
473
                w = p.Width
1✔
474
                h = p.Height
1✔
475
        )
1✔
476

1✔
477
        // Apply adaptive fit-in: swap dimensions if it would get better image definition
1✔
478
        if p.AdaptiveFitIn && w > 0 && h > 0 {
2✔
479
                imgAspect := float64(img.Width()) / float64(img.PageHeight())
1✔
480
                boxAspect := float64(w) / float64(h)
1✔
481
                // If orientations differ (one portrait, one landscape), swap dimensions
1✔
482
                if (imgAspect > 1) != (boxAspect > 1) {
2✔
483
                        w, h = h, w
1✔
484
                }
1✔
485
        }
486

487
        if w == 0 && h == 0 {
2✔
488
                w = img.Width()
1✔
489
                h = img.PageHeight()
1✔
490
        } else if w == 0 {
3✔
491
                w = img.Width() * h / img.PageHeight()
1✔
492
                if !upscale && w > img.Width() {
1✔
493
                        w = img.Width()
×
494
                }
×
495
        } else if h == 0 {
2✔
496
                h = img.PageHeight() * w / img.Width()
1✔
497
                if !upscale && h > img.PageHeight() {
1✔
498
                        h = img.PageHeight()
×
499
                }
×
500
        }
501
        if !thumbnail {
2✔
502
                if p.FitIn {
2✔
503
                        // Calculate dimensions for full-fit-in
1✔
504
                        if p.FullFitIn && w > 0 && h > 0 {
2✔
505
                                imgAspect := float64(img.Width()) / float64(img.PageHeight())
1✔
506
                                boxAspect := float64(w) / float64(h)
1✔
507

1✔
508
                                if imgAspect < boxAspect {
2✔
509
                                        // Image is taller (portrait) - use width as constraint, height will exceed box
1✔
510
                                        h = int(float64(w) / imgAspect)
1✔
511
                                } else {
2✔
512
                                        // Image is wider (landscape) - use height as constraint, width will exceed box
1✔
513
                                        w = int(float64(h) * imgAspect)
1✔
514
                                }
1✔
515
                        }
516

517
                        if upscale || w < img.Width() || h < img.PageHeight() {
2✔
518
                                opts := &vips.ThumbnailImageOptions{Height: h, Crop: vips.InterestingNone}
1✔
519
                                if err := img.ThumbnailImage(w, opts); err != nil {
1✔
UNCOV
520
                                        return err
×
521
                                }
×
522
                        }
523
                } else if stretch {
2✔
524
                        if upscale || (w < img.Width() && h < img.PageHeight()) {
2✔
525
                                if err := img.ThumbnailImage(
1✔
526
                                        w, &vips.ThumbnailImageOptions{Height: h, Crop: vips.InterestingNone, Size: vips.SizeForce},
1✔
527
                                ); err != nil {
1✔
528
                                        return err
×
529
                                }
×
530
                        }
531
                } else if upscale || w < img.Width() || h < img.PageHeight() {
2✔
532
                        interest := vips.InterestingCentre
1✔
533
                        if p.Smart {
1✔
534
                                interest = vips.InterestingAttention
×
535
                        } else if float64(w)/float64(h) > float64(img.Width())/float64(img.PageHeight()) {
2✔
536
                                if p.VAlign == imagorpath.VAlignTop {
2✔
537
                                        interest = vips.InterestingLow
1✔
538
                                } else if p.VAlign == imagorpath.VAlignBottom {
3✔
539
                                        interest = vips.InterestingHigh
1✔
540
                                }
1✔
541
                        } else {
1✔
542
                                if p.HAlign == imagorpath.HAlignLeft {
2✔
543
                                        interest = vips.InterestingLow
1✔
544
                                } else if p.HAlign == imagorpath.HAlignRight {
3✔
545
                                        interest = vips.InterestingHigh
1✔
546
                                }
1✔
547
                        }
548
                        if len(focalRects) > 0 {
2✔
549
                                focalX, focalY := parseFocalPoint(focalRects...)
1✔
550
                                if err := v.FocalThumbnail(
1✔
551
                                        img, w, h,
1✔
552
                                        (focalX-cropLeft)/float64(img.Width()),
1✔
553
                                        (focalY-cropTop)/float64(img.PageHeight()),
1✔
554
                                ); err != nil {
1✔
555
                                        return err
×
556
                                }
×
557
                        } else {
1✔
558
                                if err := v.Thumbnail(img, w, h, interest, vips.SizeBoth); err != nil {
1✔
559
                                        return err
×
560
                                }
×
561
                        }
562
                        if _, err := v.CheckResolution(img, nil); err != nil {
1✔
563
                                return err
×
564
                        }
×
565
                }
566
        }
567
        if p.HFlip {
2✔
568
                if err := img.Flip(vips.DirectionHorizontal); err != nil {
1✔
569
                        return err
×
570
                }
×
571
        }
572
        if p.VFlip {
2✔
573
                if err := img.Flip(vips.DirectionVertical); err != nil {
1✔
574
                        return err
×
575
                }
×
576
        }
577
        for i, filter := range p.Filters {
2✔
578
                if err := ctx.Err(); err != nil {
1✔
579
                        return err
×
580
                }
×
581
                if v.disableFilters[filter.Name] {
2✔
582
                        continue
1✔
583
                }
584
                if v.MaxFilterOps > 0 && i >= v.MaxFilterOps {
2✔
585
                        if v.Debug {
2✔
586
                                v.Logger.Debug("max-filter-ops-exceeded",
1✔
587
                                        zap.String("name", filter.Name), zap.String("args", filter.Args))
1✔
588
                        }
1✔
589
                        break
1✔
590
                }
591
                start := time.Now()
1✔
592
                var args []string
1✔
593
                if filter.Args != "" {
2✔
594
                        args = imagorpath.SplitArgs(filter.Args)
1✔
595
                }
1✔
596
                if fn := v.Filters[filter.Name]; fn != nil {
2✔
597
                        if err := fn(ctx, img, load, args...); err != nil {
1✔
598
                                return err
×
599
                        }
×
600
                } else if filter.Name == "fill" {
2✔
601
                        if err := v.fill(ctx, img, w, h,
1✔
602
                                p.PaddingLeft, p.PaddingTop, p.PaddingRight, p.PaddingBottom,
1✔
603
                                filter.Args); err != nil {
1✔
604
                                return err
×
605
                        }
×
606
                }
607
                if v.Debug {
2✔
608
                        v.Logger.Debug("filter",
1✔
609
                                zap.String("name", filter.Name), zap.String("args", filter.Args),
1✔
610
                                zap.Duration("took", time.Since(start)))
1✔
611
                }
1✔
612
        }
613
        return nil
1✔
614
}
615

616
// Metadata image attributes
617
type Metadata struct {
618
        Format      string            `json:"format"`
619
        ContentType string            `json:"content_type"`
620
        Width       int               `json:"width"`
621
        Height      int               `json:"height"`
622
        Orientation int               `json:"orientation"`
623
        Pages       int               `json:"pages"`
624
        Bands       int               `json:"bands"`
625
        Exif        map[string]string `json:"exif"`
626
}
627

628
func metadata(img *vips.Image, format vips.ImageType, stripExif bool) *Metadata {
1✔
629
        pages := 1
1✔
630
        if IsAnimationSupported(format) {
2✔
631
                pages = img.Height() / img.PageHeight()
1✔
632
        }
1✔
633
        if format == vips.ImageTypePdf {
2✔
634
                pages = img.Pages()
1✔
635
        }
1✔
636
        exif := map[string]string{}
1✔
637
        if !stripExif {
2✔
638
                exif = extractExif(img.Exif())
1✔
639
        }
1✔
640
        mimeType, _ := format.MimeType()
1✔
641
        return &Metadata{
1✔
642
                Format:      string(format),
1✔
643
                ContentType: mimeType,
1✔
644
                Width:       img.Width(),
1✔
645
                Height:      img.PageHeight(),
1✔
646
                Pages:       pages,
1✔
647
                Bands:       img.Bands(),
1✔
648
                Orientation: img.Orientation(),
1✔
649
                Exif:        exif,
1✔
650
        }
1✔
651
}
652

653
func supportedSaveFormat(format vips.ImageType) vips.ImageType {
1✔
654
        switch format {
1✔
655
        case vips.ImageTypePng, vips.ImageTypeWebp, vips.ImageTypeTiff, vips.ImageTypeGif, vips.ImageTypeAvif, vips.ImageTypeHeif, vips.ImageTypeJp2k, vips.ImageTypeJxl:
1✔
656
                return format
1✔
657
        }
658
        return vips.ImageTypeJpeg
1✔
659
}
660

661
func (v *Processor) export(
662
        image *vips.Image, format vips.ImageType, compression int, quality int, palette bool, bitdepth int, stripMetadata bool,
663
) ([]byte, error) {
1✔
664
        // check resolution before export
1✔
665
        if _, err := v.CheckResolution(image, nil); err != nil {
1✔
666
                return nil, err
×
667
        }
×
668
        switch format {
1✔
669
        case vips.ImageTypePng:
1✔
670
                opts := &vips.PngsaveBufferOptions{
1✔
671
                        Q:           quality,
1✔
672
                        Palette:     palette,
1✔
673
                        Bitdepth:    bitdepth,
1✔
674
                        Compression: compression,
1✔
675
                }
1✔
676
                if stripMetadata {
2✔
677
                        opts.Keep = vips.KeepNone
1✔
678
                }
1✔
679
                return image.PngsaveBuffer(opts)
1✔
680
        case vips.ImageTypeWebp:
1✔
681
                opts := &vips.WebpsaveBufferOptions{
1✔
682
                        Q: quality,
1✔
683
                }
1✔
684
                if stripMetadata {
2✔
685
                        opts.Keep = vips.KeepNone
1✔
686
                }
1✔
687
                return image.WebpsaveBuffer(opts)
1✔
688
        case vips.ImageTypeJxl:
1✔
689
                opts := &vips.JxlsaveBufferOptions{
1✔
690
                        Q: quality,
1✔
691
                }
1✔
692
                if stripMetadata {
1✔
693
                        opts.Keep = vips.KeepNone
×
694
                }
×
695
                return image.JxlsaveBuffer(opts)
1✔
696
        case vips.ImageTypeTiff:
1✔
697
                opts := &vips.TiffsaveBufferOptions{
1✔
698
                        Q: quality,
1✔
699
                }
1✔
700
                if stripMetadata {
2✔
701
                        opts.Keep = vips.KeepNone
1✔
702
                }
1✔
703
                return image.TiffsaveBuffer(opts)
1✔
704
        case vips.ImageTypeGif:
1✔
705
                opts := &vips.GifsaveBufferOptions{}
1✔
706
                if stripMetadata {
2✔
707
                        opts.Keep = vips.KeepNone
1✔
708
                }
1✔
709
                return image.GifsaveBuffer(opts)
1✔
710
        case vips.ImageTypeAvif:
1✔
711
                opts := &vips.HeifsaveBufferOptions{
1✔
712
                        Q:           quality,
1✔
713
                        Compression: vips.HeifCompressionAv1,
1✔
714
                }
1✔
715
                if stripMetadata {
2✔
716
                        opts.Keep = vips.KeepNone
1✔
717
                }
1✔
718
                opts.Effort = 9 - v.AvifSpeed
1✔
719
                return image.HeifsaveBuffer(opts)
1✔
720
        case vips.ImageTypeHeif:
1✔
721
                opts := &vips.HeifsaveBufferOptions{
1✔
722
                        Q: quality,
1✔
723
                }
1✔
724
                if stripMetadata {
1✔
725
                        opts.Keep = vips.KeepNone
×
726
                }
×
727
                return image.HeifsaveBuffer(opts)
1✔
728
        case vips.ImageTypeJp2k:
×
729
                opts := &vips.Jp2ksaveBufferOptions{
×
730
                        Q: quality,
×
731
                }
×
732
                if stripMetadata {
×
733
                        opts.Keep = vips.KeepNone
×
734
                }
×
735
                return image.Jp2ksaveBuffer(opts)
×
736
        default:
1✔
737
                opts := &vips.JpegsaveBufferOptions{}
1✔
738
                if v.MozJPEG {
1✔
739
                        opts.Q = 75
×
740
                        opts.Keep = vips.KeepNone
×
741
                        opts.OptimizeCoding = true
×
742
                        opts.Interlace = true
×
743
                        opts.OptimizeScans = true
×
744
                        opts.TrellisQuant = true
×
745
                        opts.QuantTable = 3
×
746
                }
×
747
                if quality > 0 {
2✔
748
                        opts.Q = quality
1✔
749
                }
1✔
750
                if stripMetadata {
2✔
751
                        opts.Keep = vips.KeepNone
1✔
752
                }
1✔
753
                return image.JpegsaveBuffer(opts)
1✔
754
        }
755
}
756

757
func argSplit(r rune) bool {
1✔
758
        return r == 'x' || r == ',' || r == ':'
1✔
759
}
1✔
760

761
type focal struct {
762
        Left   float64
763
        Right  float64
764
        Top    float64
765
        Bottom float64
766
}
767

768
func parseFocalPoint(focalRects ...focal) (focalX, focalY float64) {
1✔
769
        var sumWeight float64
1✔
770
        for _, f := range focalRects {
2✔
771
                sumWeight += (f.Right - f.Left) * (f.Bottom - f.Top)
1✔
772
        }
1✔
773
        for _, f := range focalRects {
2✔
774
                r := (f.Right - f.Left) * (f.Bottom - f.Top) / sumWeight
1✔
775
                focalX += (f.Left + f.Right) / 2 * r
1✔
776
                focalY += (f.Top + f.Bottom) / 2 * r
1✔
777
        }
1✔
778
        return
1✔
779
}
780

781
func findTrim(
782
        _ context.Context, img *vips.Image, pos string, tolerance int,
783
) (l, t, w, h int, err error) {
1✔
784
        if isAnimated(img) {
2✔
785
                // skip animation support
1✔
786
                return
1✔
787
        }
1✔
788
        tmp, err := img.Copy(&vips.CopyOptions{Interpretation: vips.InterpretationSrgb})
1✔
789
        if err != nil {
1✔
790
                return
×
791
        }
×
792
        defer tmp.Close()
1✔
793
        if tmp.HasAlpha() {
2✔
794
                if err = tmp.Flatten(&vips.FlattenOptions{Background: []float64{255, 0, 255}}); err != nil {
1✔
795
                        return
×
796
                }
×
797
        }
798
        var x, y int
1✔
799
        if pos == imagorpath.TrimByBottomRight {
2✔
800
                x = tmp.Width() - 1
1✔
801
                y = tmp.PageHeight() - 1
1✔
802
        }
1✔
803
        if tolerance == 0 {
2✔
804
                tolerance = 1
1✔
805
        }
1✔
806
        background, err := tmp.Getpoint(x, y, nil)
1✔
807
        if err != nil {
1✔
808
                return
×
809
        }
×
810
        l, t, w, h, err = tmp.FindTrim(&vips.FindTrimOptions{
1✔
811
                Threshold:  float64(tolerance),
1✔
812
                Background: background,
1✔
813
        })
1✔
814
        return
1✔
815
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc