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

cshum / imagor / 21593031391

02 Feb 2026 02:00PM UTC coverage: 91.91% (+0.04%) from 91.871%
21593031391

Pull #720

github

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

140 of 147 new or added lines in 1 file covered. (95.24%)

1 existing line in 1 file now uncovered.

5601 of 6094 relevant lines covered (91.91%)

1.1 hits per line

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

87.85
/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✔
NEW
82
                        return nil, WrapErr(err)
×
NEW
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✔
NEW
102
                                default:
×
NEW
103
                                        params.quality = params.quality * 75 / 100
×
104
                                }
105
                                if err := ctx.Err(); err != nil {
1✔
NEW
106
                                        return nil, WrapErr(err)
×
NEW
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 {
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✔
UNCOV
239
                case "dpi":
×
NEW
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
        if w == 0 && h == 0 {
2✔
477
                w = img.Width()
1✔
478
                h = img.PageHeight()
1✔
479
        } else if w == 0 {
3✔
480
                w = img.Width() * h / img.PageHeight()
1✔
481
                if !upscale && w > img.Width() {
1✔
482
                        w = img.Width()
×
483
                }
×
484
        } else if h == 0 {
2✔
485
                h = img.PageHeight() * w / img.Width()
1✔
486
                if !upscale && h > img.PageHeight() {
1✔
487
                        h = img.PageHeight()
×
488
                }
×
489
        }
490
        if !thumbnail {
2✔
491
                if p.FitIn {
2✔
492
                        if upscale || w < img.Width() || h < img.PageHeight() {
2✔
493
                                if err := img.ThumbnailImage(w, &vips.ThumbnailImageOptions{Height: h, Crop: vips.InterestingNone}); err != nil {
1✔
494
                                        return err
×
495
                                }
×
496
                        }
497
                } else if stretch {
2✔
498
                        if upscale || (w < img.Width() && h < img.PageHeight()) {
2✔
499
                                if err := img.ThumbnailImage(
1✔
500
                                        w, &vips.ThumbnailImageOptions{Height: h, Crop: vips.InterestingNone, Size: vips.SizeForce},
1✔
501
                                ); err != nil {
1✔
502
                                        return err
×
503
                                }
×
504
                        }
505
                } else if upscale || w < img.Width() || h < img.PageHeight() {
2✔
506
                        interest := vips.InterestingCentre
1✔
507
                        if p.Smart {
1✔
508
                                interest = vips.InterestingAttention
×
509
                        } else if float64(w)/float64(h) > float64(img.Width())/float64(img.PageHeight()) {
2✔
510
                                if p.VAlign == imagorpath.VAlignTop {
2✔
511
                                        interest = vips.InterestingLow
1✔
512
                                } else if p.VAlign == imagorpath.VAlignBottom {
3✔
513
                                        interest = vips.InterestingHigh
1✔
514
                                }
1✔
515
                        } else {
1✔
516
                                if p.HAlign == imagorpath.HAlignLeft {
2✔
517
                                        interest = vips.InterestingLow
1✔
518
                                } else if p.HAlign == imagorpath.HAlignRight {
3✔
519
                                        interest = vips.InterestingHigh
1✔
520
                                }
1✔
521
                        }
522
                        if len(focalRects) > 0 {
2✔
523
                                focalX, focalY := parseFocalPoint(focalRects...)
1✔
524
                                if err := v.FocalThumbnail(
1✔
525
                                        img, w, h,
1✔
526
                                        (focalX-cropLeft)/float64(img.Width()),
1✔
527
                                        (focalY-cropTop)/float64(img.PageHeight()),
1✔
528
                                ); err != nil {
1✔
529
                                        return err
×
530
                                }
×
531
                        } else {
1✔
532
                                if err := v.Thumbnail(img, w, h, interest, vips.SizeBoth); err != nil {
1✔
533
                                        return err
×
534
                                }
×
535
                        }
536
                        if _, err := v.CheckResolution(img, nil); err != nil {
1✔
537
                                return err
×
538
                        }
×
539
                }
540
        }
541
        if p.HFlip {
2✔
542
                if err := img.Flip(vips.DirectionHorizontal); err != nil {
1✔
543
                        return err
×
544
                }
×
545
        }
546
        if p.VFlip {
2✔
547
                if err := img.Flip(vips.DirectionVertical); err != nil {
1✔
548
                        return err
×
549
                }
×
550
        }
551
        for i, filter := range p.Filters {
2✔
552
                if err := ctx.Err(); err != nil {
1✔
553
                        return err
×
554
                }
×
555
                if v.disableFilters[filter.Name] {
2✔
556
                        continue
1✔
557
                }
558
                if v.MaxFilterOps > 0 && i >= v.MaxFilterOps {
2✔
559
                        if v.Debug {
2✔
560
                                v.Logger.Debug("max-filter-ops-exceeded",
1✔
561
                                        zap.String("name", filter.Name), zap.String("args", filter.Args))
1✔
562
                        }
1✔
563
                        break
1✔
564
                }
565
                start := time.Now()
1✔
566
                var args []string
1✔
567
                if filter.Args != "" {
2✔
568
                        args = strings.Split(filter.Args, ",")
1✔
569
                }
1✔
570
                if fn := v.Filters[filter.Name]; fn != nil {
2✔
571
                        if err := fn(ctx, img, load, args...); err != nil {
1✔
572
                                return err
×
573
                        }
×
574
                } else if filter.Name == "fill" {
2✔
575
                        if err := v.fill(ctx, img, w, h,
1✔
576
                                p.PaddingLeft, p.PaddingTop, p.PaddingRight, p.PaddingBottom,
1✔
577
                                filter.Args); err != nil {
1✔
578
                                return err
×
579
                        }
×
580
                }
581
                if v.Debug {
2✔
582
                        v.Logger.Debug("filter",
1✔
583
                                zap.String("name", filter.Name), zap.String("args", filter.Args),
1✔
584
                                zap.Duration("took", time.Since(start)))
1✔
585
                }
1✔
586
        }
587
        return nil
1✔
588
}
589

590
// Metadata image attributes
591
type Metadata struct {
592
        Format      string            `json:"format"`
593
        ContentType string            `json:"content_type"`
594
        Width       int               `json:"width"`
595
        Height      int               `json:"height"`
596
        Orientation int               `json:"orientation"`
597
        Pages       int               `json:"pages"`
598
        Bands       int               `json:"bands"`
599
        Exif        map[string]string `json:"exif"`
600
}
601

602
func metadata(img *vips.Image, format vips.ImageType, stripExif bool) *Metadata {
1✔
603
        pages := 1
1✔
604
        if IsAnimationSupported(format) {
2✔
605
                pages = img.Height() / img.PageHeight()
1✔
606
        }
1✔
607
        if format == vips.ImageTypePdf {
2✔
608
                pages = img.Pages()
1✔
609
        }
1✔
610
        exif := map[string]string{}
1✔
611
        if !stripExif {
2✔
612
                exif = extractExif(img.Exif())
1✔
613
        }
1✔
614
        mimeType, _ := format.MimeType()
1✔
615
        return &Metadata{
1✔
616
                Format:      string(format),
1✔
617
                ContentType: mimeType,
1✔
618
                Width:       img.Width(),
1✔
619
                Height:      img.PageHeight(),
1✔
620
                Pages:       pages,
1✔
621
                Bands:       img.Bands(),
1✔
622
                Orientation: img.Orientation(),
1✔
623
                Exif:        exif,
1✔
624
        }
1✔
625
}
626

627
func supportedSaveFormat(format vips.ImageType) vips.ImageType {
1✔
628
        switch format {
1✔
629
        case vips.ImageTypePng, vips.ImageTypeWebp, vips.ImageTypeTiff, vips.ImageTypeGif, vips.ImageTypeAvif, vips.ImageTypeHeif, vips.ImageTypeJp2k, vips.ImageTypeJxl:
1✔
630
                return format
1✔
631
        }
632
        return vips.ImageTypeJpeg
1✔
633
}
634

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

731
func argSplit(r rune) bool {
1✔
732
        return r == 'x' || r == ',' || r == ':'
1✔
733
}
1✔
734

735
type focal struct {
736
        Left   float64
737
        Right  float64
738
        Top    float64
739
        Bottom float64
740
}
741

742
func parseFocalPoint(focalRects ...focal) (focalX, focalY float64) {
1✔
743
        var sumWeight float64
1✔
744
        for _, f := range focalRects {
2✔
745
                sumWeight += (f.Right - f.Left) * (f.Bottom - f.Top)
1✔
746
        }
1✔
747
        for _, f := range focalRects {
2✔
748
                r := (f.Right - f.Left) * (f.Bottom - f.Top) / sumWeight
1✔
749
                focalX += (f.Left + f.Right) / 2 * r
1✔
750
                focalY += (f.Top + f.Bottom) / 2 * r
1✔
751
        }
1✔
752
        return
1✔
753
}
754

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