forked from cshum/imagor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
image.go
730 lines (619 loc) · 17 KB
/
image.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
package vips
// #include "vips.h"
import "C"
import (
"errors"
"fmt"
"strconv"
"strings"
"sync"
)
// Image contains a libvips image and manages its lifecycle.
type Image struct {
// NOTE: We keep a reference to this so that the input buffer is
// never garbage collected during processing. Some image loaders use random
// access transcoding and therefore need the original buffer to be in memory.
buf []byte
image *C.VipsImage
format ImageType
lock sync.Mutex
pageHeight int // cached page height
}
// Param libvips options param
type Param struct {
value interface{}
isSet bool
}
// IsSet is param set
func (p *Param) IsSet() bool {
return p.isSet
}
func (p *Param) set(v interface{}) {
p.value = v
p.isSet = true
}
// BoolParam bool param
type BoolParam struct {
Param
}
// Set bool param
func (p *BoolParam) Set(v bool) {
p.set(v)
}
// Get bool param
func (p *BoolParam) Get() bool {
return p.value.(bool)
}
// IntParam int param
type IntParam struct {
Param
}
// Set int param
func (p *IntParam) Set(v int) {
p.set(v)
}
// Get int param
func (p *IntParam) Get() int {
return p.value.(int)
}
// ImportParams are options for loading an image. Some are type-specific.
// For default loading, use NewImportParams() or specify nil
type ImportParams struct {
AutoRotate BoolParam
FailOnError BoolParam
Page IntParam
NumPages IntParam
Density IntParam
JpegShrinkFactor IntParam
HeifThumbnail BoolParam
SvgUnlimited BoolParam
}
// NewImportParams creates default ImportParams
func NewImportParams() *ImportParams {
p := &ImportParams{}
p.FailOnError.Set(true)
return p
}
// OptionString convert import params to option_string
func (i *ImportParams) OptionString() string {
var values []string
if v := i.NumPages; v.IsSet() {
values = append(values, "n="+strconv.Itoa(v.Get()))
}
if v := i.Page; v.IsSet() {
values = append(values, "page="+strconv.Itoa(v.Get()))
}
if v := i.Density; v.IsSet() {
values = append(values, "dpi="+strconv.Itoa(v.Get()))
}
if v := i.FailOnError; v.IsSet() {
values = append(values, "fail="+boolToStr(v.Get()))
}
if v := i.JpegShrinkFactor; v.IsSet() {
values = append(values, "shrink="+strconv.Itoa(v.Get()))
}
if v := i.AutoRotate; v.IsSet() {
values = append(values, "autorotate="+boolToStr(v.Get()))
}
if v := i.SvgUnlimited; v.IsSet() {
values = append(values, "unlimited="+boolToStr(v.Get()))
}
if v := i.HeifThumbnail; v.IsSet() {
values = append(values, "thumbnail="+boolToStr(v.Get()))
}
return strings.Join(values, ",")
}
// LoadImageFromSource loads a Source and creates a new Image
func LoadImageFromSource(s *Source, params *ImportParams) (*Image, error) {
if params == nil {
params = NewImportParams()
}
vipsImage, format, err := vipsImageFromSource(s.src, params)
if err != nil {
return nil, err
}
ref := newImageRef(vipsImage, format, nil)
log("vips", LogLevelDebug, fmt.Sprintf("created imageRef %p", ref))
return ref, nil
}
// LoadThumbnailFromSource loads a Source and creates a new Image with thumbnail crop and resize
func LoadThumbnailFromSource(s *Source, width, height int, crop Interesting, size Size, params *ImportParams) (*Image, error) {
if params == nil {
params = NewImportParams()
}
vipsImage, format, err := vipsThumbnailFromSource(
s.src, width, height, crop, size, params)
if err != nil {
return nil, err
}
ref := newImageRef(vipsImage, format, nil)
log("vips", LogLevelDebug, fmt.Sprintf("created imageRef %p", ref))
return ref, nil
}
// LoadImageFromBuffer loads an image buffer and creates a new Image
func LoadImageFromBuffer(buf []byte, params *ImportParams) (*Image, error) {
startupIfNeeded()
if params == nil {
params = NewImportParams()
}
vipsImage, format, err := vipsImageFromBuffer(buf, params)
if err != nil {
return nil, err
}
ref := newImageRef(vipsImage, format, buf)
log("vips", LogLevelDebug, fmt.Sprintf("created imageRef %p", ref))
return ref, nil
}
// LoadImageFromMemory loads a raw RGB/RGBA image buffer and creates a new Image
func LoadImageFromMemory(buf []byte, width, height, bands int) (*Image, error) {
startupIfNeeded()
vipsImage, format, err := vipsImageFromMemory(buf, width, height, bands)
if err != nil {
return nil, err
}
ref := newImageRef(vipsImage, format, buf)
log("vips", LogLevelDebug, fmt.Sprintf("created imageRef %p", ref))
return ref, nil
}
// Copy creates a new copy of the given image.
func (r *Image) Copy() (*Image, error) {
out, err := vipsCopyImage(r.image)
if err != nil {
return nil, err
}
return newImageRef(out, r.format, r.buf), nil
}
func newImageRef(vipsImage *C.VipsImage, format ImageType, buf []byte) *Image {
imageRef := &Image{
image: vipsImage,
format: format,
buf: buf,
}
return imageRef
}
// Close closes the image and frees the memory
func (r *Image) Close() {
r.lock.Lock()
if r.image != nil {
clearImage(r.image)
r.image = nil
log("vips", LogLevelDebug, fmt.Sprintf("closing image %p", r))
}
r.buf = nil
r.lock.Unlock()
}
// Format returns the initial format of the vips image when loaded.
func (r *Image) Format() ImageType {
return r.format
}
// Width returns the width of this image.
func (r *Image) Width() int {
return int(r.image.Xsize)
}
// Height returns the height of this image.
func (r *Image) Height() int {
return int(r.image.Ysize)
}
// Bands returns the number of bands for this image.
func (r *Image) Bands() int {
return int(r.image.Bands)
}
// HasAlpha returns if the image has an alpha layer.
func (r *Image) HasAlpha() bool {
return vipsHasAlpha(r.image)
}
// Orientation returns the orientation number as it appears in the Exif, if present
func (r *Image) Orientation() int {
return vipsGetMetaOrientation(r.image)
}
// Interpretation returns the current interpretation of the color space of the image.
func (r *Image) Interpretation() Interpretation {
return Interpretation(int(r.image.Type))
}
// ColorSpace returns the interpretation of the current color space. Alias to Interpretation().
func (r *Image) ColorSpace() Interpretation {
return r.Interpretation()
}
// Pages returns the number of pages in the Image
// For animated images this corresponds to the number of frames
func (r *Image) Pages() int {
// libvips uses the same attribute (n_pages) to represent the number of pyramid layers in JP2K
// as we interpret the attribute as frames and JP2K does not support animation we override this with 1
if r.format == ImageTypeJP2K {
return 1
}
return vipsGetImageNPages(r.image)
}
// PageHeight return the height of a single page
func (r *Image) PageHeight() int {
if r.pageHeight == 0 {
r.pageHeight = vipsGetPageHeight(r.image)
}
return r.pageHeight
}
// SetPageHeight set the height of a page
// For animated images this is used when "unrolling" back to frames
func (r *Image) SetPageHeight(height int) error {
out, err := vipsCopyImage(r.image)
if err != nil {
return err
}
vipsSetPageHeight(out, height)
r.setImage(out)
return nil
}
// SetPageDelay set the page delay array for animation
func (r *Image) SetPageDelay(delay []int) error {
var data []C.int
for _, d := range delay {
data = append(data, C.int(d))
}
return vipsImageSetDelay(r.image, data)
}
// Exif extracts Exif key value data
func (r *Image) Exif() map[string]any {
return vipsImageGetExif(r.image)
}
// ExportJpeg exports the image as JPEG to a buffer.
func (r *Image) ExportJpeg(params *JpegExportParams) ([]byte, error) {
if params == nil {
params = NewJpegExportParams()
}
buf, err := vipsSaveJPEGToBuffer(r.image, *params)
if err != nil {
return nil, err
}
return buf, nil
}
// ExportPng exports the image as PNG to a buffer.
func (r *Image) ExportPng(params *PngExportParams) ([]byte, error) {
if params == nil {
params = NewPngExportParams()
}
buf, err := vipsSavePNGToBuffer(r.image, *params)
if err != nil {
return nil, err
}
return buf, nil
}
// ExportWebp exports the image as WEBP to a buffer.
func (r *Image) ExportWebp(params *WebpExportParams) ([]byte, error) {
if params == nil {
params = NewWebpExportParams()
}
buf, err := vipsSaveWebPToBuffer(r.image, *params)
if err != nil {
return nil, err
}
return buf, nil
}
// ExportHeif exports the image as HEIF to a buffer.
func (r *Image) ExportHeif(params *HeifExportParams) ([]byte, error) {
if params == nil {
params = NewHeifExportParams()
}
buf, err := vipsSaveHEIFToBuffer(r.image, *params)
if err != nil {
return nil, err
}
return buf, nil
}
// ExportTiff exports the image as TIFF to a buffer.
func (r *Image) ExportTiff(params *TiffExportParams) ([]byte, error) {
if params == nil {
params = NewTiffExportParams()
}
buf, err := vipsSaveTIFFToBuffer(r.image, *params)
if err != nil {
return nil, err
}
return buf, nil
}
// ExportGIF exports the image as GIF to a buffer.
func (r *Image) ExportGIF(params *GifExportParams) ([]byte, error) {
if params == nil {
params = NewGifExportParams()
}
buf, err := vipsSaveGIFToBuffer(r.image, *params)
if err != nil {
return nil, err
}
return buf, nil
}
// ExportAvif exports the image as AVIF to a buffer.
func (r *Image) ExportAvif(params *AvifExportParams) ([]byte, error) {
if params == nil {
params = NewAvifExportParams()
}
buf, err := vipsSaveAVIFToBuffer(r.image, *params)
if err != nil {
return nil, err
}
return buf, nil
}
// ExportJp2k exports the image as JPEG2000 to a buffer.
func (r *Image) ExportJp2k(params *Jp2kExportParams) ([]byte, error) {
if params == nil {
params = NewJp2kExportParams()
}
buf, err := vipsSaveJP2KToBuffer(r.image, *params)
if err != nil {
return nil, err
}
return buf, nil
}
// Composite composites the given overlay image on top of the associated image with provided blending mode.
func (r *Image) Composite(overlay *Image, mode BlendMode, x, y int) error {
out, err := vipsComposite2(r.image, overlay.image, mode, x, y)
if err != nil {
return err
}
r.setImage(out)
return nil
}
// AddAlpha adds an alpha channel to the associated image.
func (r *Image) AddAlpha() error {
if vipsHasAlpha(r.image) {
return nil
}
out, err := vipsAddAlpha(r.image)
if err != nil {
return err
}
r.setImage(out)
return nil
}
// Linear passes an image through a linear transformation (i.e. output = input * a + b).
// See https://libvips.github.io/libvips/API/current/libvips-arithmetic.html#vips-linear
func (r *Image) Linear(a, b []float64) error {
if len(a) != len(b) {
return errors.New("a and b must be of same length")
}
out, err := vipsLinear(r.image, a, b, len(a))
if err != nil {
return err
}
r.setImage(out)
return nil
}
// ExtractArea crops the image to a specified area
func (r *Image) ExtractArea(left, top, width, height int) error {
if r.Height() > r.PageHeight() {
// use animated extract area if more than 1 page loaded
out, err := vipsExtractAreaMultiPage(r.image, left, top, width, height)
if err != nil {
return err
}
r.setImage(out)
} else {
out, err := vipsExtractArea(r.image, left, top, width, height)
if err != nil {
return err
}
r.setImage(out)
}
return nil
}
// RemoveICCProfile removes the ICC Profile information from the image.
// Typically, browsers and other software assume images without profile to be in the sRGB color space.
func (r *Image) RemoveICCProfile() error {
out, err := vipsCopyImage(r.image)
if err != nil {
return err
}
vipsRemoveICCProfile(out)
r.setImage(out)
return nil
}
// RemoveExif removes Exif metadata from the image.
func (r *Image) RemoveExif() error {
out, err := vipsRemoveExif(r.image)
if err != nil {
return err
}
r.setImage(out)
return nil
}
// ToColorSpace changes the color space of the image to the interpretation supplied as the parameter.
func (r *Image) ToColorSpace(interpretation Interpretation) error {
out, err := vipsToColorSpace(r.image, interpretation)
if err != nil {
return err
}
r.setImage(out)
return nil
}
// Flatten removes the alpha channel from the image and replaces it with the background color
func (r *Image) Flatten(backgroundColor *Color) error {
out, err := vipsFlatten(r.image, backgroundColor)
if err != nil {
return err
}
r.setImage(out)
return nil
}
// Label adds text label with font, dimensions, alignment, color and opacity
func (r *Image) Label(
text, font string,
x, y, size int, align Align,
color *Color, opacity float64,
) error {
out, err := vipsLabel(r.image, text, font,
x, y, size, align, color, opacity)
if err != nil {
return err
}
r.setImage(out)
return nil
}
// GaussianBlur blurs the image
func (r *Image) GaussianBlur(sigma float64) error {
out, err := vipsGaussianBlur(r.image, sigma)
if err != nil {
return err
}
r.setImage(out)
return nil
}
// Sharpen sharpens the image
// sigma: sigma of the gaussian
// x1: flat/jaggy threshold
// m2: slope for jaggy areas
func (r *Image) Sharpen(sigma float64, x1 float64, m2 float64) error {
out, err := vipsSharpen(r.image, sigma, x1, m2)
if err != nil {
return err
}
r.setImage(out)
return nil
}
// Modulate the colors
func (r *Image) Modulate(brightness, saturation, hue float64) error {
var err error
var multiplications []float64
var additions []float64
colorspace := r.ColorSpace()
if colorspace == InterpretationRGB {
colorspace = InterpretationSRGB
}
multiplications = []float64{brightness, saturation, 1}
additions = []float64{0, 0, hue}
if r.HasAlpha() {
multiplications = append(multiplications, 1)
additions = append(additions, 0)
}
err = r.ToColorSpace(InterpretationLCH)
if err != nil {
return err
}
err = r.Linear(multiplications, additions)
if err != nil {
return err
}
err = r.ToColorSpace(colorspace)
if err != nil {
return err
}
return nil
}
// FindTrim returns the bounding box of the non-border part of the image
// Returned values are left, top, width, height
func (r *Image) FindTrim(threshold float64, x, y int) (int, int, int, int, error) {
return vipsFindTrim(r.image, threshold, x, y)
}
// GetPoint reads a single pixel on an image.
// The pixel values are returned in a slice of length n.
func (r *Image) GetPoint(x int, y int) ([]float64, error) {
n := 3
if vipsHasAlpha(r.image) {
n = 4
}
return vipsGetPoint(r.image, n, x, y)
}
// Thumbnail resizes the image to the given width and height.
// crop decides algorithm vips uses to shrink and crop to fill target,
func (r *Image) Thumbnail(width, height int, crop Interesting) error {
return r.ThumbnailWithSize(width, height, crop, SizeBoth)
}
// ThumbnailWithSize resizes the image to the given width and height.
// crop decides algorithm vips uses to shrink and crop to fill target,
// size controls upsize, downsize, both or force
func (r *Image) ThumbnailWithSize(width, height int, crop Interesting, size Size) error {
out, err := vipsThumbnail(r.image, width, height, crop, size)
if err != nil {
return err
}
r.setImage(out)
return nil
}
// Embed embeds the given picture in a new one, i.e. the opposite of ExtractArea
func (r *Image) Embed(left, top, width, height int, extend ExtendStrategy) error {
if r.Height() > r.PageHeight() {
out, err := vipsEmbedMultiPage(r.image, left, top, width, height, extend)
if err != nil {
return err
}
r.setImage(out)
} else {
out, err := vipsEmbed(r.image, left, top, width, height, extend)
if err != nil {
return err
}
r.setImage(out)
}
return nil
}
// EmbedBackground embeds the given picture with a background color
func (r *Image) EmbedBackground(left, top, width, height int, backgroundColor *Color) error {
return r.EmbedBackgroundRGBA(left, top, width, height, &ColorRGBA{
R: backgroundColor.R,
G: backgroundColor.G,
B: backgroundColor.B,
A: 255,
})
}
// EmbedBackgroundRGBA embeds the given picture with a background rgba color
func (r *Image) EmbedBackgroundRGBA(left, top, width, height int, backgroundColor *ColorRGBA) error {
if r.Height() > r.PageHeight() {
out, err := vipsEmbedMultiPageBackground(r.image, left, top, width, height, backgroundColor)
if err != nil {
return err
}
r.setImage(out)
} else {
out, err := vipsEmbedBackground(r.image, left, top, width, height, backgroundColor)
if err != nil {
return err
}
r.setImage(out)
}
return nil
}
// Flip flips the image either horizontally or vertically based on the parameter
func (r *Image) Flip(direction Direction) error {
out, err := vipsFlip(r.image, direction)
if err != nil {
return err
}
r.setImage(out)
return nil
}
// Rotate rotates the image by multiples of 90 degrees
func (r *Image) Rotate(angle Angle) error {
if r.Height() > r.PageHeight() {
out, err := vipsRotateMultiPage(r.image, angle)
if err != nil {
return err
}
r.setImage(out)
} else {
out, err := vipsRotate(r.image, angle)
if err != nil {
return err
}
r.setImage(out)
}
return nil
}
// Replicate repeats an image many times across and down
func (r *Image) Replicate(across int, down int) error {
out, err := vipsReplicate(r.image, across, down)
if err != nil {
return err
}
r.setImage(out)
return nil
}
// setImage resets the image for this image and frees the previous one
func (r *Image) setImage(image *C.VipsImage) {
r.lock.Lock()
defer r.lock.Unlock()
if r.image == image {
return
}
if r.image != nil {
clearImage(r.image)
}
r.image = image
r.pageHeight = 0
}