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

cshum / imagor / 21592866362

02 Feb 2026 01:53PM UTC coverage: 91.895% (+0.02%) from 91.871%
21592866362

Pull #720

github

cshum
refactor vips process
Pull Request #720: refactor: vips process func conslidation

147 of 155 new or added lines in 1 file covered. (94.84%)

54 existing lines in 1 file now uncovered.

5601 of 6095 relevant lines covered (91.89%)

1.1 hits per line

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

87.72
/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, params, 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
        // Handle metadata response
1✔
63
        if p.Meta {
2✔
64
                stripExif := false
1✔
65
                for _, f := range p.Filters {
2✔
66
                        if f.Name == "strip_exif" {
2✔
67
                                stripExif = true
1✔
68
                                break
1✔
69
                        }
70
                }
71
                return imagor.NewBlobFromJsonMarshal(metadata(img, params.format, stripExif)), nil
1✔
72
        }
73

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

116
// loadAndProcess loads the image from blob and applies all transformations
117
func (v *Processor) loadAndProcess(
118
        ctx context.Context, blob *imagor.Blob, p imagorpath.Params, load imagor.LoadFunc,
119
) (*vips.Image, *exportParams, error) {
1✔
120
        var (
1✔
121
                thumbnailNotSupported bool
1✔
122
                upscale               = true
1✔
123
                stretch               = p.Stretch
1✔
124
                thumbnail             = false
1✔
125
                stripMetadata         = v.StripMetadata
1✔
126
                orient                int
1✔
127
                img                   *vips.Image
1✔
128
                format                = vips.ImageTypeUnknown
1✔
129
                maxN                  = v.MaxAnimationFrames
1✔
130
                maxBytes              int
1✔
131
                page                  = 1
1✔
132
                dpi                   = 0
1✔
133
                focalRects            []focal
1✔
134
                err                   error
1✔
135
        )
1✔
136
        if p.Trim || p.VFlip {
2✔
137
                thumbnailNotSupported = true
1✔
138
        }
1✔
139
        if p.FitIn {
2✔
140
                upscale = false
1✔
141
        }
1✔
142
        if maxN == 0 || maxN < -1 {
2✔
143
                maxN = 1
1✔
144
        }
1✔
145
        if blob != nil && !blob.SupportsAnimation() {
2✔
146
                maxN = 1
1✔
147
        }
1✔
148
        for _, p := range p.Filters {
2✔
149
                if v.disableFilters[p.Name] {
2✔
150
                        continue
1✔
151
                }
152
                switch p.Name {
1✔
153
                case "format":
1✔
154
                        if imageType, ok := imageTypeMap[p.Args]; ok {
2✔
155
                                format = supportedSaveFormat(imageType)
1✔
156
                                if !IsAnimationSupported(format) {
2✔
157
                                        // no frames if export format not support animation
1✔
158
                                        maxN = 1
1✔
159
                                }
1✔
160
                        }
161
                        break
1✔
162
                case "max_frames":
1✔
163
                        if n, _ := strconv.Atoi(p.Args); n > 0 && (maxN == -1 || n < maxN) {
2✔
164
                                maxN = n
1✔
165
                        }
1✔
166
                        break
1✔
167
                case "stretch":
1✔
168
                        stretch = true
1✔
169
                        break
1✔
170
                case "upscale":
1✔
171
                        upscale = true
1✔
172
                        break
1✔
173
                case "no_upscale":
1✔
174
                        upscale = false
1✔
175
                        break
1✔
176
                case "fill", "background_color":
1✔
177
                        if args := strings.Split(p.Args, ","); args[0] == "auto" {
2✔
178
                                thumbnailNotSupported = true
1✔
179
                        }
1✔
180
                        break
1✔
181
                case "page":
1✔
182
                        if n, _ := strconv.Atoi(p.Args); n > 0 {
2✔
183
                                page = n
1✔
184
                        }
1✔
185
                        break
1✔
UNCOV
186
                case "dpi":
×
UNCOV
187
                        if n, _ := strconv.Atoi(p.Args); n > 0 {
×
UNCOV
188
                                dpi = n
×
UNCOV
189
                        }
×
UNCOV
190
                        break
×
191
                case "orient":
1✔
192
                        if n, _ := strconv.Atoi(p.Args); n > 0 {
2✔
193
                                orient = n
1✔
194
                                thumbnailNotSupported = true
1✔
195
                        }
1✔
196
                        break
1✔
197
                case "max_bytes":
1✔
198
                        if n, _ := strconv.Atoi(p.Args); n > 0 {
2✔
199
                                maxBytes = n
1✔
200
                                thumbnailNotSupported = true
1✔
201
                        }
1✔
202
                        break
1✔
203
                case "trim", "focal", "rotate":
1✔
204
                        thumbnailNotSupported = true
1✔
205
                        break
1✔
206
                case "strip_metadata":
1✔
207
                        stripMetadata = true
1✔
208
                        break
1✔
209
                }
210
        }
211

212
        if !thumbnailNotSupported &&
1✔
213
                p.CropBottom == 0.0 && p.CropTop == 0.0 && p.CropLeft == 0.0 && p.CropRight == 0.0 {
2✔
214
                // apply shrink-on-load where possible
1✔
215
                if p.FitIn {
2✔
216
                        if p.Width > 0 || p.Height > 0 {
2✔
217
                                w := p.Width
1✔
218
                                h := p.Height
1✔
219
                                if w == 0 {
2✔
220
                                        w = v.MaxWidth
1✔
221
                                }
1✔
222
                                if h == 0 {
2✔
223
                                        h = v.MaxHeight
1✔
224
                                }
1✔
225
                                size := vips.SizeDown
1✔
226
                                if upscale {
2✔
227
                                        size = vips.SizeBoth
1✔
228
                                }
1✔
229
                                if img, err = v.NewThumbnail(
1✔
230
                                        ctx, blob, w, h, vips.InterestingNone, size, maxN, page, dpi,
1✔
231
                                ); err != nil {
1✔
NEW
232
                                        return nil, nil, err
×
UNCOV
233
                                }
×
234
                                thumbnail = true
1✔
235
                        }
236
                } else if stretch {
2✔
237
                        if p.Width > 0 && p.Height > 0 {
2✔
238
                                if img, err = v.NewThumbnail(
1✔
239
                                        ctx, blob, p.Width, p.Height,
1✔
240
                                        vips.InterestingNone, vips.SizeForce, maxN, page, dpi,
1✔
241
                                ); err != nil {
1✔
242
                                        return nil, nil, err
×
243
                                }
×
244
                                thumbnail = true
1✔
245
                        }
246
                } else {
1✔
247
                        if p.Width > 0 && p.Height > 0 {
2✔
248
                                interest := vips.InterestingNone
1✔
249
                                if p.Smart {
2✔
250
                                        interest = vips.InterestingAttention
1✔
251
                                        thumbnail = true
1✔
252
                                } else if (p.VAlign == imagorpath.VAlignTop && p.HAlign == "") ||
2✔
253
                                        (p.HAlign == imagorpath.HAlignLeft && p.VAlign == "") {
2✔
254
                                        interest = vips.InterestingLow
1✔
255
                                        thumbnail = true
1✔
256
                                } else if (p.VAlign == imagorpath.VAlignBottom && p.HAlign == "") ||
2✔
257
                                        (p.HAlign == imagorpath.HAlignRight && p.VAlign == "") {
2✔
258
                                        interest = vips.InterestingHigh
1✔
259
                                        thumbnail = true
1✔
260
                                } else if (p.VAlign == "" || p.VAlign == "middle") &&
2✔
261
                                        (p.HAlign == "" || p.HAlign == "center") {
2✔
262
                                        interest = vips.InterestingCentre
1✔
263
                                        thumbnail = true
1✔
264
                                }
1✔
265
                                if thumbnail {
2✔
266
                                        if img, err = v.NewThumbnail(
1✔
267
                                                ctx, blob, p.Width, p.Height,
1✔
268
                                                interest, vips.SizeBoth, maxN, page, dpi,
1✔
269
                                        ); err != nil {
2✔
270
                                                return nil, nil, err
1✔
271
                                        }
1✔
272
                                }
273
                        } else if p.Width > 0 && p.Height == 0 {
2✔
274
                                if img, err = v.NewThumbnail(
1✔
275
                                        ctx, blob, p.Width, v.MaxHeight,
1✔
276
                                        vips.InterestingNone, vips.SizeBoth, maxN, page, dpi,
1✔
277
                                ); err != nil {
2✔
278
                                        return nil, nil, err
1✔
279
                                }
1✔
280
                                thumbnail = true
1✔
281
                        } else if p.Height > 0 && p.Width == 0 {
2✔
282
                                if img, err = v.NewThumbnail(
1✔
283
                                        ctx, blob, v.MaxWidth, p.Height,
1✔
284
                                        vips.InterestingNone, vips.SizeBoth, maxN, page, dpi,
1✔
285
                                ); err != nil {
1✔
UNCOV
286
                                        return nil, nil, err
×
287
                                }
×
288
                                thumbnail = true
1✔
289
                        }
290
                }
291
        }
292
        if !thumbnail {
2✔
293
                if thumbnailNotSupported {
2✔
294
                        if img, err = v.NewImage(ctx, blob, maxN, page, dpi); err != nil {
1✔
UNCOV
295
                                return nil, nil, err
×
UNCOV
296
                        }
×
297
                } else {
1✔
298
                        if img, err = v.NewThumbnail(
1✔
299
                                ctx, blob, v.MaxWidth, v.MaxHeight,
1✔
300
                                vips.InterestingNone, vips.SizeDown, maxN, page, dpi,
1✔
301
                        ); err != nil {
2✔
302
                                return nil, nil, err
1✔
303
                        }
1✔
304
                }
305
        }
306

307
        if orient > 0 {
2✔
308
                // orient rotate before resize
1✔
309
                if err = img.RotMultiPage(getAngle(orient)); err != nil {
1✔
UNCOV
310
                        return nil, nil, err
×
UNCOV
311
                }
×
312
        }
313
        var (
1✔
314
                quality     int
1✔
315
                bitdepth    int
1✔
316
                compression int
1✔
317
                palette     bool
1✔
318
                origWidth   = float64(img.Width())
1✔
319
                origHeight  = float64(img.PageHeight())
1✔
320
        )
1✔
321
        if format == vips.ImageTypeUnknown {
2✔
322
                if blob.BlobType() == imagor.BlobTypeAVIF {
2✔
323
                        // meta loader determined as heif
1✔
324
                        format = vips.ImageTypeAvif
1✔
325
                } else {
2✔
326
                        format = img.Format()
1✔
327
                }
1✔
328
        }
329
        if v.Debug {
2✔
330
                v.Logger.Debug("image",
1✔
331
                        zap.Int("width", img.Width()),
1✔
332
                        zap.Int("height", img.Height()),
1✔
333
                        zap.Int("page_height", img.PageHeight()))
1✔
334
        }
1✔
335
        for _, p := range p.Filters {
2✔
336
                if v.disableFilters[p.Name] {
2✔
337
                        continue
1✔
338
                }
339
                switch p.Name {
1✔
340
                case "quality":
1✔
341
                        quality, _ = strconv.Atoi(p.Args)
1✔
342
                        break
1✔
343
                case "autojpg":
1✔
344
                        format = vips.ImageTypeJpeg
1✔
345
                        break
1✔
346
                case "focal":
1✔
347
                        args := strings.FieldsFunc(p.Args, argSplit)
1✔
348
                        switch len(args) {
1✔
349
                        case 4:
1✔
350
                                f := focal{}
1✔
351
                                f.Left, _ = strconv.ParseFloat(args[0], 64)
1✔
352
                                f.Top, _ = strconv.ParseFloat(args[1], 64)
1✔
353
                                f.Right, _ = strconv.ParseFloat(args[2], 64)
1✔
354
                                f.Bottom, _ = strconv.ParseFloat(args[3], 64)
1✔
355
                                if f.Left < 1 && f.Top < 1 && f.Right <= 1 && f.Bottom <= 1 {
2✔
356
                                        f.Left *= origWidth
1✔
357
                                        f.Right *= origWidth
1✔
358
                                        f.Top *= origHeight
1✔
359
                                        f.Bottom *= origHeight
1✔
360
                                }
1✔
361
                                if f.Right > f.Left && f.Bottom > f.Top {
2✔
362
                                        focalRects = append(focalRects, f)
1✔
363
                                }
1✔
364
                        case 2:
1✔
365
                                f := focal{}
1✔
366
                                f.Left, _ = strconv.ParseFloat(args[0], 64)
1✔
367
                                f.Top, _ = strconv.ParseFloat(args[1], 64)
1✔
368
                                if f.Left < 1 && f.Top < 1 {
2✔
369
                                        f.Left *= origWidth
1✔
370
                                        f.Top *= origHeight
1✔
371
                                }
1✔
372
                                f.Right = f.Left + 1
1✔
373
                                f.Bottom = f.Top + 1
1✔
374
                                focalRects = append(focalRects, f)
1✔
375
                        }
376
                        break
1✔
377
                case "palette":
1✔
378
                        palette = true
1✔
379
                        break
1✔
380
                case "bitdepth":
1✔
381
                        bitdepth, _ = strconv.Atoi(p.Args)
1✔
382
                        break
1✔
383
                case "compression":
1✔
384
                        compression, _ = strconv.Atoi(p.Args)
1✔
385
                        break
1✔
386
                }
387
        }
388
        // Apply transformations
389
        if err := v.applyTransformations(ctx, img, p, load, thumbnail, stretch, upscale, focalRects); err != nil {
1✔
UNCOV
390
                return nil, nil, WrapErr(err)
×
NEW
391
        }
×
392

393
        // Return processed image and export parameters
394
        params := &exportParams{
1✔
395
                format:        format,
1✔
396
                quality:       quality,
1✔
397
                compression:   compression,
1✔
398
                bitdepth:      bitdepth,
1✔
399
                palette:       palette,
1✔
400
                stripMetadata: stripMetadata,
1✔
401
                maxBytes:      maxBytes,
1✔
402
        }
1✔
403
        return img, params, nil
1✔
404
}
405

406
// applyTransformations applies all image transformations (crop, resize, flip, filters)
407
func (v *Processor) applyTransformations(
408
        ctx context.Context, img *vips.Image, p imagorpath.Params, load imagor.LoadFunc, thumbnail, stretch, upscale bool, focalRects []focal,
409
) error {
1✔
410
        var (
1✔
411
                origWidth  = float64(img.Width())
1✔
412
                origHeight = float64(img.PageHeight())
1✔
413
                cropLeft,
1✔
414
                cropTop,
1✔
415
                cropRight,
1✔
416
                cropBottom float64
1✔
417
        )
1✔
418
        if p.CropRight > 0 || p.CropLeft > 0 || p.CropBottom > 0 || p.CropTop > 0 {
2✔
419
                // percentage
1✔
420
                cropLeft = math.Max(p.CropLeft, 0)
1✔
421
                cropTop = math.Max(p.CropTop, 0)
1✔
422
                cropRight = p.CropRight
1✔
423
                cropBottom = p.CropBottom
1✔
424
                if p.CropLeft < 1 && p.CropTop < 1 && p.CropRight <= 1 && p.CropBottom <= 1 {
2✔
425
                        cropLeft = math.Round(cropLeft * origWidth)
1✔
426
                        cropTop = math.Round(cropTop * origHeight)
1✔
427
                        cropRight = math.Round(cropRight * origWidth)
1✔
428
                        cropBottom = math.Round(cropBottom * origHeight)
1✔
429
                }
1✔
430
                if cropRight == 0 {
2✔
431
                        cropRight = origWidth - 1
1✔
432
                }
1✔
433
                if cropBottom == 0 {
2✔
434
                        cropBottom = origHeight - 1
1✔
435
                }
1✔
436
                cropRight = math.Min(cropRight, origWidth-1)
1✔
437
                cropBottom = math.Min(cropBottom, origHeight-1)
1✔
438
        }
439
        if p.Trim {
2✔
440
                if l, t, w, h, err := findTrim(ctx, img, p.TrimBy, p.TrimTolerance); err == nil {
2✔
441
                        cropLeft = math.Max(cropLeft, float64(l))
1✔
442
                        cropTop = math.Max(cropTop, float64(t))
1✔
443
                        if cropRight > 0 {
2✔
444
                                cropRight = math.Min(cropRight, float64(l+w))
1✔
445
                        } else {
2✔
446
                                cropRight = float64(l + w)
1✔
447
                        }
1✔
448
                        if cropBottom > 0 {
2✔
449
                                cropBottom = math.Min(cropBottom, float64(t+h))
1✔
450
                        } else {
2✔
451
                                cropBottom = float64(t + h)
1✔
452
                        }
1✔
453
                }
454
        }
455
        if cropRight > cropLeft && cropBottom > cropTop {
2✔
456
                if err := img.ExtractAreaMultiPage(
1✔
457
                        int(cropLeft), int(cropTop), int(cropRight-cropLeft), int(cropBottom-cropTop),
1✔
458
                ); err != nil {
1✔
UNCOV
459
                        return err
×
UNCOV
460
                }
×
461
        }
462
        var (
1✔
463
                w = p.Width
1✔
464
                h = p.Height
1✔
465
        )
1✔
466
        if w == 0 && h == 0 {
2✔
467
                w = img.Width()
1✔
468
                h = img.PageHeight()
1✔
469
        } else if w == 0 {
3✔
470
                w = img.Width() * h / img.PageHeight()
1✔
471
                if !upscale && w > img.Width() {
1✔
UNCOV
472
                        w = img.Width()
×
UNCOV
473
                }
×
474
        } else if h == 0 {
2✔
475
                h = img.PageHeight() * w / img.Width()
1✔
476
                if !upscale && h > img.PageHeight() {
1✔
UNCOV
477
                        h = img.PageHeight()
×
UNCOV
478
                }
×
479
        }
480
        if !thumbnail {
2✔
481
                if p.FitIn {
2✔
482
                        if upscale || w < img.Width() || h < img.PageHeight() {
2✔
483
                                if err := img.ThumbnailImage(w, &vips.ThumbnailImageOptions{Height: h, Crop: vips.InterestingNone}); err != nil {
1✔
UNCOV
484
                                        return err
×
UNCOV
485
                                }
×
486
                        }
487
                } else if stretch {
2✔
488
                        if upscale || (w < img.Width() && h < img.PageHeight()) {
2✔
489
                                if err := img.ThumbnailImage(
1✔
490
                                        w, &vips.ThumbnailImageOptions{Height: h, Crop: vips.InterestingNone, Size: vips.SizeForce},
1✔
491
                                ); err != nil {
1✔
UNCOV
492
                                        return err
×
UNCOV
493
                                }
×
494
                        }
495
                } else if upscale || w < img.Width() || h < img.PageHeight() {
2✔
496
                        interest := vips.InterestingCentre
1✔
497
                        if p.Smart {
1✔
UNCOV
498
                                interest = vips.InterestingAttention
×
499
                        } else if float64(w)/float64(h) > float64(img.Width())/float64(img.PageHeight()) {
2✔
500
                                if p.VAlign == imagorpath.VAlignTop {
2✔
501
                                        interest = vips.InterestingLow
1✔
502
                                } else if p.VAlign == imagorpath.VAlignBottom {
3✔
503
                                        interest = vips.InterestingHigh
1✔
504
                                }
1✔
505
                        } else {
1✔
506
                                if p.HAlign == imagorpath.HAlignLeft {
2✔
507
                                        interest = vips.InterestingLow
1✔
508
                                } else if p.HAlign == imagorpath.HAlignRight {
3✔
509
                                        interest = vips.InterestingHigh
1✔
510
                                }
1✔
511
                        }
512
                        if len(focalRects) > 0 {
2✔
513
                                focalX, focalY := parseFocalPoint(focalRects...)
1✔
514
                                if err := v.FocalThumbnail(
1✔
515
                                        img, w, h,
1✔
516
                                        (focalX-cropLeft)/float64(img.Width()),
1✔
517
                                        (focalY-cropTop)/float64(img.PageHeight()),
1✔
518
                                ); err != nil {
1✔
UNCOV
519
                                        return err
×
UNCOV
520
                                }
×
521
                        } else {
1✔
522
                                if err := v.Thumbnail(img, w, h, interest, vips.SizeBoth); err != nil {
1✔
UNCOV
523
                                        return err
×
UNCOV
524
                                }
×
525
                        }
526
                        if _, err := v.CheckResolution(img, nil); err != nil {
1✔
UNCOV
527
                                return err
×
UNCOV
528
                        }
×
529
                }
530
        }
531
        if p.HFlip {
2✔
532
                if err := img.Flip(vips.DirectionHorizontal); err != nil {
1✔
533
                        return err
×
534
                }
×
535
        }
536
        if p.VFlip {
2✔
537
                if err := img.Flip(vips.DirectionVertical); err != nil {
1✔
538
                        return err
×
UNCOV
539
                }
×
540
        }
541
        for i, filter := range p.Filters {
2✔
542
                if err := ctx.Err(); err != nil {
1✔
543
                        return err
×
544
                }
×
545
                if v.disableFilters[filter.Name] {
2✔
546
                        continue
1✔
547
                }
548
                if v.MaxFilterOps > 0 && i >= v.MaxFilterOps {
2✔
549
                        if v.Debug {
2✔
550
                                v.Logger.Debug("max-filter-ops-exceeded",
1✔
551
                                        zap.String("name", filter.Name), zap.String("args", filter.Args))
1✔
552
                        }
1✔
553
                        break
1✔
554
                }
555
                start := time.Now()
1✔
556
                var args []string
1✔
557
                if filter.Args != "" {
2✔
558
                        args = strings.Split(filter.Args, ",")
1✔
559
                }
1✔
560
                if fn := v.Filters[filter.Name]; fn != nil {
2✔
561
                        if err := fn(ctx, img, load, args...); err != nil {
1✔
UNCOV
562
                                return err
×
UNCOV
563
                        }
×
564
                } else if filter.Name == "fill" {
2✔
565
                        if err := v.fill(ctx, img, w, h,
1✔
566
                                p.PaddingLeft, p.PaddingTop, p.PaddingRight, p.PaddingBottom,
1✔
567
                                filter.Args); err != nil {
1✔
UNCOV
568
                                return err
×
UNCOV
569
                        }
×
570
                }
571
                if v.Debug {
2✔
572
                        v.Logger.Debug("filter",
1✔
573
                                zap.String("name", filter.Name), zap.String("args", filter.Args),
1✔
574
                                zap.Duration("took", time.Since(start)))
1✔
575
                }
1✔
576
        }
577
        return nil
1✔
578
}
579

580
// Metadata image attributes
581
type Metadata struct {
582
        Format      string            `json:"format"`
583
        ContentType string            `json:"content_type"`
584
        Width       int               `json:"width"`
585
        Height      int               `json:"height"`
586
        Orientation int               `json:"orientation"`
587
        Pages       int               `json:"pages"`
588
        Bands       int               `json:"bands"`
589
        Exif        map[string]string `json:"exif"`
590
}
591

592
func metadata(img *vips.Image, format vips.ImageType, stripExif bool) *Metadata {
1✔
593
        pages := 1
1✔
594
        if IsAnimationSupported(format) {
2✔
595
                pages = img.Height() / img.PageHeight()
1✔
596
        }
1✔
597
        if format == vips.ImageTypePdf {
2✔
598
                pages = img.Pages()
1✔
599
        }
1✔
600
        exif := map[string]string{}
1✔
601
        if !stripExif {
2✔
602
                exif = extractExif(img.Exif())
1✔
603
        }
1✔
604
        mimeType, _ := format.MimeType()
1✔
605
        return &Metadata{
1✔
606
                Format:      string(format),
1✔
607
                ContentType: mimeType,
1✔
608
                Width:       img.Width(),
1✔
609
                Height:      img.PageHeight(),
1✔
610
                Pages:       pages,
1✔
611
                Bands:       img.Bands(),
1✔
612
                Orientation: img.Orientation(),
1✔
613
                Exif:        exif,
1✔
614
        }
1✔
615
}
616

617
func supportedSaveFormat(format vips.ImageType) vips.ImageType {
1✔
618
        switch format {
1✔
619
        case vips.ImageTypePng, vips.ImageTypeWebp, vips.ImageTypeTiff, vips.ImageTypeGif, vips.ImageTypeAvif, vips.ImageTypeHeif, vips.ImageTypeJp2k, vips.ImageTypeJxl:
1✔
620
                return format
1✔
621
        }
622
        return vips.ImageTypeJpeg
1✔
623
}
624

625
func (v *Processor) export(
626
        image *vips.Image, format vips.ImageType, compression int, quality int, palette bool, bitdepth int, stripMetadata bool,
627
) ([]byte, error) {
1✔
628
        // check resolution before export
1✔
629
        if _, err := v.CheckResolution(image, nil); err != nil {
1✔
UNCOV
630
                return nil, err
×
UNCOV
631
        }
×
632
        switch format {
1✔
633
        case vips.ImageTypePng:
1✔
634
                opts := &vips.PngsaveBufferOptions{
1✔
635
                        Q:           quality,
1✔
636
                        Palette:     palette,
1✔
637
                        Bitdepth:    bitdepth,
1✔
638
                        Compression: compression,
1✔
639
                }
1✔
640
                if stripMetadata {
2✔
641
                        opts.Keep = vips.KeepNone
1✔
642
                }
1✔
643
                return image.PngsaveBuffer(opts)
1✔
644
        case vips.ImageTypeWebp:
1✔
645
                opts := &vips.WebpsaveBufferOptions{
1✔
646
                        Q: quality,
1✔
647
                }
1✔
648
                if stripMetadata {
2✔
649
                        opts.Keep = vips.KeepNone
1✔
650
                }
1✔
651
                return image.WebpsaveBuffer(opts)
1✔
652
        case vips.ImageTypeJxl:
1✔
653
                opts := &vips.JxlsaveBufferOptions{
1✔
654
                        Q: quality,
1✔
655
                }
1✔
656
                if stripMetadata {
1✔
UNCOV
657
                        opts.Keep = vips.KeepNone
×
UNCOV
658
                }
×
659
                return image.JxlsaveBuffer(opts)
1✔
660
        case vips.ImageTypeTiff:
1✔
661
                opts := &vips.TiffsaveBufferOptions{
1✔
662
                        Q: quality,
1✔
663
                }
1✔
664
                if stripMetadata {
2✔
665
                        opts.Keep = vips.KeepNone
1✔
666
                }
1✔
667
                return image.TiffsaveBuffer(opts)
1✔
668
        case vips.ImageTypeGif:
1✔
669
                opts := &vips.GifsaveBufferOptions{}
1✔
670
                if stripMetadata {
2✔
671
                        opts.Keep = vips.KeepNone
1✔
672
                }
1✔
673
                return image.GifsaveBuffer(opts)
1✔
674
        case vips.ImageTypeAvif:
1✔
675
                opts := &vips.HeifsaveBufferOptions{
1✔
676
                        Q:           quality,
1✔
677
                        Compression: vips.HeifCompressionAv1,
1✔
678
                }
1✔
679
                if stripMetadata {
2✔
680
                        opts.Keep = vips.KeepNone
1✔
681
                }
1✔
682
                opts.Effort = 9 - v.AvifSpeed
1✔
683
                return image.HeifsaveBuffer(opts)
1✔
684
        case vips.ImageTypeHeif:
1✔
685
                opts := &vips.HeifsaveBufferOptions{
1✔
686
                        Q: quality,
1✔
687
                }
1✔
688
                if stripMetadata {
1✔
UNCOV
689
                        opts.Keep = vips.KeepNone
×
UNCOV
690
                }
×
691
                return image.HeifsaveBuffer(opts)
1✔
UNCOV
692
        case vips.ImageTypeJp2k:
×
UNCOV
693
                opts := &vips.Jp2ksaveBufferOptions{
×
UNCOV
694
                        Q: quality,
×
UNCOV
695
                }
×
UNCOV
696
                if stripMetadata {
×
UNCOV
697
                        opts.Keep = vips.KeepNone
×
UNCOV
698
                }
×
699
                return image.Jp2ksaveBuffer(opts)
×
700
        default:
1✔
701
                opts := &vips.JpegsaveBufferOptions{}
1✔
702
                if v.MozJPEG {
1✔
703
                        opts.Q = 75
×
704
                        opts.Keep = vips.KeepNone
×
705
                        opts.OptimizeCoding = true
×
706
                        opts.Interlace = true
×
707
                        opts.OptimizeScans = true
×
708
                        opts.TrellisQuant = true
×
709
                        opts.QuantTable = 3
×
UNCOV
710
                }
×
711
                if quality > 0 {
2✔
712
                        opts.Q = quality
1✔
713
                }
1✔
714
                if stripMetadata {
2✔
715
                        opts.Keep = vips.KeepNone
1✔
716
                }
1✔
717
                return image.JpegsaveBuffer(opts)
1✔
718
        }
719
}
720

721
func argSplit(r rune) bool {
1✔
722
        return r == 'x' || r == ',' || r == ':'
1✔
723
}
1✔
724

725
type focal struct {
726
        Left   float64
727
        Right  float64
728
        Top    float64
729
        Bottom float64
730
}
731

732
func parseFocalPoint(focalRects ...focal) (focalX, focalY float64) {
1✔
733
        var sumWeight float64
1✔
734
        for _, f := range focalRects {
2✔
735
                sumWeight += (f.Right - f.Left) * (f.Bottom - f.Top)
1✔
736
        }
1✔
737
        for _, f := range focalRects {
2✔
738
                r := (f.Right - f.Left) * (f.Bottom - f.Top) / sumWeight
1✔
739
                focalX += (f.Left + f.Right) / 2 * r
1✔
740
                focalY += (f.Top + f.Bottom) / 2 * r
1✔
741
        }
1✔
742
        return
1✔
743
}
744

745
func findTrim(
746
        _ context.Context, img *vips.Image, pos string, tolerance int,
747
) (l, t, w, h int, err error) {
1✔
748
        if isAnimated(img) {
2✔
749
                // skip animation support
1✔
750
                return
1✔
751
        }
1✔
752
        tmp, err := img.Copy(&vips.CopyOptions{Interpretation: vips.InterpretationSrgb})
1✔
753
        if err != nil {
1✔
UNCOV
754
                return
×
UNCOV
755
        }
×
756
        defer tmp.Close()
1✔
757
        if tmp.HasAlpha() {
2✔
758
                if err = tmp.Flatten(&vips.FlattenOptions{Background: []float64{255, 0, 255}}); err != nil {
1✔
UNCOV
759
                        return
×
UNCOV
760
                }
×
761
        }
762
        var x, y int
1✔
763
        if pos == imagorpath.TrimByBottomRight {
2✔
764
                x = tmp.Width() - 1
1✔
765
                y = tmp.PageHeight() - 1
1✔
766
        }
1✔
767
        if tolerance == 0 {
2✔
768
                tolerance = 1
1✔
769
        }
1✔
770
        background, err := tmp.Getpoint(x, y, nil)
1✔
771
        if err != nil {
1✔
UNCOV
772
                return
×
UNCOV
773
        }
×
774
        l, t, w, h, err = tmp.FindTrim(&vips.FindTrimOptions{
1✔
775
                Threshold:  float64(tolerance),
1✔
776
                Background: background,
1✔
777
        })
1✔
778
        return
1✔
779
}
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