/
image.go
2009 lines (1718 loc) · 52.8 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
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package vips
// #include "image.h"
import "C"
import (
"bytes"
"errors"
"fmt"
"image"
"io"
"os"
"runtime"
"strconv"
"strings"
"sync"
"unsafe"
)
const GaussBlurDefaultMinAMpl = 0.2
// PreMultiplicationState stores the pre-multiplication band format of the image
type PreMultiplicationState struct {
bandFormat BandFormat
}
// ImageRef contains a libvips image and manages its lifecycle.
type ImageRef 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
originalFormat ImageType
lock sync.Mutex
preMultiplication *PreMultiplicationState
optimizedIccProfile string
}
// ImageMetadata is a data structure holding the width, height, orientation and other metadata of the picture.
type ImageMetadata struct {
Format ImageType
Width int
Height int
Colorspace Interpretation
Orientation int
Pages int
}
type Parameter struct {
value interface{}
isSet bool
}
func (p *Parameter) IsSet() bool {
return p.isSet
}
func (p *Parameter) set(v interface{}) {
p.value = v
p.isSet = true
}
type BoolParameter struct {
Parameter
}
func (p *BoolParameter) Set(v bool) {
p.set(v)
}
func (p *BoolParameter) Get() bool {
return p.value.(bool)
}
type IntParameter struct {
Parameter
}
func (p *IntParameter) Set(v int) {
p.set(v)
}
func (p *IntParameter) Get() int {
return p.value.(int)
}
type Float64Parameter struct {
Parameter
}
func (p *Float64Parameter) Set(v float64) {
p.set(v)
}
func (p *Float64Parameter) Get() float64 {
return p.value.(float64)
}
// ImportParams are options for loading an image. Some are type-specific.
// For default loading, use NewImportParams() or specify nil
type ImportParams struct {
AutoRotate BoolParameter
FailOnError BoolParameter
Page IntParameter
NumPages IntParameter
Density IntParameter
JpegShrinkFactor IntParameter
HeifThumbnail BoolParameter
SvgUnlimited BoolParameter
}
// 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, ",")
}
func boolToStr(v bool) string {
if v {
return "TRUE"
}
return "FALSE"
}
// ExportParams are options when exporting an image to file or buffer.
// Deprecated: Use format-specific params
type ExportParams struct {
Format ImageType
Quality int
Compression int
Interlaced bool
Lossless bool
Effort int
StripMetadata bool
OptimizeCoding bool // jpeg param
SubsampleMode SubsampleMode // jpeg param
TrellisQuant bool // jpeg param
OvershootDeringing bool // jpeg param
OptimizeScans bool // jpeg param
QuantTable int // jpeg param
Speed int // avif param
}
// NewDefaultExportParams creates default values for an export when image type is not JPEG, PNG or WEBP.
// By default, govips creates interlaced, lossy images with a quality of 80/100 and compression of 6/10.
// As these are default values for a wide variety of image formats, their application varies.
// Some formats use the quality parameters, some compression, etc.
// Deprecated: Use format-specific params
func NewDefaultExportParams() *ExportParams {
return &ExportParams{
Format: ImageTypeUnknown, // defaults to the starting encoder
Quality: 80,
Compression: 6,
Interlaced: true,
Lossless: false,
Effort: 4,
}
}
// NewDefaultJPEGExportParams creates default values for an export of a JPEG image.
// By default, govips creates interlaced JPEGs with a quality of 80/100.
// Deprecated: Use NewJpegExportParams
func NewDefaultJPEGExportParams() *ExportParams {
return &ExportParams{
Format: ImageTypeJPEG,
Quality: 80,
Interlaced: true,
}
}
// NewDefaultPNGExportParams creates default values for an export of a PNG image.
// By default, govips creates non-interlaced PNGs with a compression of 6/10.
// Deprecated: Use NewPngExportParams
func NewDefaultPNGExportParams() *ExportParams {
return &ExportParams{
Format: ImageTypePNG,
Compression: 6,
Interlaced: false,
}
}
// NewDefaultWEBPExportParams creates default values for an export of a WEBP image.
// By default, govips creates lossy images with a quality of 75/100.
// Deprecated: Use NewWebpExportParams
func NewDefaultWEBPExportParams() *ExportParams {
return &ExportParams{
Format: ImageTypeWEBP,
Quality: 75,
Lossless: false,
Effort: 4,
}
}
// JpegExportParams are options when exporting a JPEG to file or buffer
type JpegExportParams struct {
StripMetadata bool
Quality int
Interlace bool
OptimizeCoding bool
SubsampleMode SubsampleMode
TrellisQuant bool
OvershootDeringing bool
OptimizeScans bool
QuantTable int
}
// NewJpegExportParams creates default values for an export of a JPEG image.
// By default, govips creates interlaced JPEGs with a quality of 80/100.
func NewJpegExportParams() *JpegExportParams {
return &JpegExportParams{
Quality: 80,
Interlace: true,
}
}
// PngExportParams are options when exporting a PNG to file or buffer
type PngExportParams struct {
StripMetadata bool
Compression int
Filter PngFilter
Interlace bool
Quality int
Palette bool
Dither float64
Bitdepth int
Profile string // TODO: Use this param during save
}
// NewPngExportParams creates default values for an export of a PNG image.
// By default, govips creates non-interlaced PNGs with a compression of 6/10.
func NewPngExportParams() *PngExportParams {
return &PngExportParams{
Compression: 6,
Filter: PngFilterNone,
Interlace: false,
Palette: false,
}
}
// WebpExportParams are options when exporting a WEBP to file or buffer
type WebpExportParams struct {
StripMetadata bool
Quality int
Lossless bool
NearLossless bool
ReductionEffort int
IccProfile string
}
// NewWebpExportParams creates default values for an export of a WEBP image.
// By default, govips creates lossy images with a quality of 75/100.
func NewWebpExportParams() *WebpExportParams {
return &WebpExportParams{
Quality: 75,
Lossless: false,
NearLossless: false,
ReductionEffort: 4,
}
}
// TiffExportParams are options when exporting a TIFF to file or buffer
type TiffExportParams struct {
StripMetadata bool
Quality int
Compression TiffCompression
Predictor TiffPredictor
}
// NewTiffExportParams creates default values for an export of a TIFF image.
func NewTiffExportParams() *TiffExportParams {
return &TiffExportParams{
Quality: 80,
Compression: TiffCompressionLzw,
Predictor: TiffPredictorHorizontal,
}
}
type GifExportParams struct {
StripMetadata bool
Quality int
Dither float64
Effort int
Bitdepth int
}
// NewGifExportParams creates default values for an export of a GIF image.
func NewGifExportParams() *GifExportParams {
return &GifExportParams{
Quality: 75,
Effort: 7,
Bitdepth: 8,
}
}
// HeifExportParams are options when exporting a HEIF to file or buffer
type HeifExportParams struct {
Quality int
Bitdepth int
Effort int
Lossless bool
}
// NewHeifExportParams creates default values for an export of a HEIF image.
func NewHeifExportParams() *HeifExportParams {
return &HeifExportParams{
Quality: 80,
Bitdepth: 8,
Effort: 5,
Lossless: false,
}
}
// AvifExportParams are options when exporting an AVIF to file or buffer.
type AvifExportParams struct {
StripMetadata bool
Quality int
Bitdepth int
Effort int
Lossless bool
// DEPRECATED - Use Effort instead.
Speed int
}
// NewAvifExportParams creates default values for an export of an AVIF image.
func NewAvifExportParams() *AvifExportParams {
return &AvifExportParams{
Quality: 80,
Bitdepth: 8,
Effort: 5,
Lossless: false,
}
}
// Jp2kExportParams are options when exporting an JPEG2000 to file or buffer.
type Jp2kExportParams struct {
Quality int
Lossless bool
TileWidth int
TileHeight int
SubsampleMode SubsampleMode
}
// NewJp2kExportParams creates default values for an export of an JPEG2000 image.
func NewJp2kExportParams() *Jp2kExportParams {
return &Jp2kExportParams{
Quality: 80,
Lossless: false,
TileWidth: 512,
TileHeight: 512,
}
}
// NewImageFromReader loads an ImageRef from the given reader
func NewImageFromReader(r io.Reader) (*ImageRef, error) {
buf, err := io.ReadAll(r)
if err != nil {
return nil, err
}
return NewImageFromBuffer(buf)
}
// NewImageFromFile loads an image from file and creates a new ImageRef
func NewImageFromFile(file string) (*ImageRef, error) {
return LoadImageFromFile(file, nil)
}
// LoadImageFromFile loads an image from file and creates a new ImageRef
func LoadImageFromFile(file string, params *ImportParams) (*ImageRef, error) {
buf, err := os.ReadFile(file)
if err != nil {
return nil, err
}
govipsLog("govips", LogLevelDebug, fmt.Sprintf("creating imageRef from file %s", file))
return LoadImageFromBuffer(buf, params)
}
// NewImageFromBuffer loads an image buffer and creates a new Image
func NewImageFromBuffer(buf []byte) (*ImageRef, error) {
return LoadImageFromBuffer(buf, nil)
}
// LoadImageFromBuffer loads an image buffer and creates a new Image
func LoadImageFromBuffer(buf []byte, params *ImportParams) (*ImageRef, error) {
startupIfNeeded()
if params == nil {
params = NewImportParams()
}
vipsImage, currentFormat, originalFormat, err := vipsLoadFromBuffer(buf, params)
if err != nil {
return nil, err
}
ref := newImageRef(vipsImage, currentFormat, originalFormat, buf)
govipsLog("govips", LogLevelDebug, fmt.Sprintf("created imageRef %p", ref))
return ref, nil
}
// NewThumbnailFromFile loads an image from file and creates a new ImageRef with thumbnail crop
func NewThumbnailFromFile(file string, width, height int, crop Interesting) (*ImageRef, error) {
return LoadThumbnailFromFile(file, width, height, crop, SizeBoth, nil)
}
// NewThumbnailFromBuffer loads an image buffer and creates a new Image with thumbnail crop
func NewThumbnailFromBuffer(buf []byte, width, height int, crop Interesting) (*ImageRef, error) {
return LoadThumbnailFromBuffer(buf, width, height, crop, SizeBoth, nil)
}
// NewThumbnailWithSizeFromFile loads an image from file and creates a new ImageRef with thumbnail crop and size
func NewThumbnailWithSizeFromFile(file string, width, height int, crop Interesting, size Size) (*ImageRef, error) {
return LoadThumbnailFromFile(file, width, height, crop, size, nil)
}
// LoadThumbnailFromFile loads an image from file and creates a new ImageRef with thumbnail crop and size
func LoadThumbnailFromFile(file string, width, height int, crop Interesting, size Size, params *ImportParams) (*ImageRef, error) {
startupIfNeeded()
vipsImage, format, err := vipsThumbnailFromFile(file, width, height, crop, size, params)
if err != nil {
return nil, err
}
ref := newImageRef(vipsImage, format, format, nil)
govipsLog("govips", LogLevelDebug, fmt.Sprintf("created imageref %p", ref))
return ref, nil
}
// NewThumbnailWithSizeFromBuffer loads an image buffer and creates a new Image with thumbnail crop and size
func NewThumbnailWithSizeFromBuffer(buf []byte, width, height int, crop Interesting, size Size) (*ImageRef, error) {
return LoadThumbnailFromBuffer(buf, width, height, crop, size, nil)
}
// LoadThumbnailFromBuffer loads an image buffer and creates a new Image with thumbnail crop and size
func LoadThumbnailFromBuffer(buf []byte, width, height int, crop Interesting, size Size, params *ImportParams) (*ImageRef, error) {
startupIfNeeded()
vipsImage, format, err := vipsThumbnailFromBuffer(buf, width, height, crop, size, params)
if err != nil {
return nil, err
}
ref := newImageRef(vipsImage, format, format, buf)
govipsLog("govips", LogLevelDebug, fmt.Sprintf("created imageref %p", ref))
return ref, nil
}
// Metadata returns the metadata (ImageMetadata struct) of the associated ImageRef
func (r *ImageRef) Metadata() *ImageMetadata {
return &ImageMetadata{
Format: r.Format(),
Width: r.Width(),
Height: r.Height(),
Orientation: r.Orientation(),
Colorspace: r.ColorSpace(),
Pages: r.Pages(),
}
}
// Copy creates a new copy of the given image.
func (r *ImageRef) Copy() (*ImageRef, error) {
out, err := vipsCopyImage(r.image)
if err != nil {
return nil, err
}
return newImageRef(out, r.format, r.originalFormat, r.buf), nil
}
// Copy creates a new copy of the given image with the new X and Y resolution (PPI).
func (r *ImageRef) CopyChangingResolution(xres, yres float64) (*ImageRef, error) {
out, err := vipsCopyImageChangingResolution(r.image, xres, yres)
if err != nil {
return nil, err
}
return newImageRef(out, r.format, r.originalFormat, r.buf), nil
}
// Copy creates a new copy of the given image with the interpretation.
func (r *ImageRef) CopyChangingInterpretation(interpretation Interpretation) (*ImageRef, error) {
out, err := vipsCopyImageChangingInterpretation(r.image, interpretation)
if err != nil {
return nil, err
}
return newImageRef(out, r.format, r.originalFormat, r.buf), nil
}
// XYZ creates a two-band uint32 image where the elements in the first band have the value of their x coordinate
// and elements in the second band have their y coordinate.
func XYZ(width, height int) (*ImageRef, error) {
vipsImage, err := vipsXYZ(width, height)
return newImageRef(vipsImage, ImageTypeUnknown, ImageTypeUnknown, nil), err
}
// Identity creates an identity lookup table, which will leave an image unchanged when applied with Maplut.
// Each entry in the table has a value equal to its position.
func Identity(ushort bool) (*ImageRef, error) {
img, err := vipsIdentity(ushort)
return newImageRef(img, ImageTypeUnknown, ImageTypeUnknown, nil), err
}
// Black creates a new black image of the specified size
func Black(width, height int) (*ImageRef, error) {
vipsImage, err := vipsBlack(width, height)
imageRef := &ImageRef{
image: vipsImage,
}
runtime.SetFinalizer(imageRef, finalizeImage)
return imageRef, err
}
// MemoryBytes creates a new image from array of bytes given width, height, bands
func MemoryBytes(buf []byte, width, height int, bands int, do_copy bool) (*ImageRef, error) {
size := width * height * bands
var vipsImage *C.VipsImage
var err error
if do_copy {
vipsImage, err = vipsMemoryCopy(buf, size, width, height, bands, C.VIPS_FORMAT_CHAR)
} else {
vipsImage, err = vipsMemory(buf, size, width, height, bands, C.VIPS_FORMAT_CHAR)
}
imageRef := &ImageRef{
image: vipsImage,
}
runtime.SetFinalizer(imageRef, finalizeImage)
return imageRef, err
}
// MemoryRGBA creates a new image from native go image.RGBA type
func MemoryRGBA(img *image.RGBA, do_copy bool) (*ImageRef, error) {
bands := 4
width, height := img.Bounds().Size().X, img.Bounds().Size().Y
size := width * height * bands
var vipsImage *C.VipsImage
var err error
if do_copy {
vipsImage, err = vipsMemoryCopy(img.Pix, size, width, height, bands, C.VIPS_FORMAT_CHAR)
} else {
vipsImage, err = vipsMemory(img.Pix, size, width, height, bands, C.VIPS_FORMAT_CHAR)
}
imageRef := &ImageRef{
image: vipsImage,
}
runtime.SetFinalizer(imageRef, finalizeImage)
return imageRef, err
}
func newImageRef(vipsImage *C.VipsImage, currentFormat ImageType, originalFormat ImageType, buf []byte) *ImageRef {
imageRef := &ImageRef{
image: vipsImage,
format: currentFormat,
originalFormat: originalFormat,
buf: buf,
}
runtime.SetFinalizer(imageRef, finalizeImage)
return imageRef
}
func finalizeImage(ref *ImageRef) {
govipsLog("govips", LogLevelDebug, fmt.Sprintf("closing image %p", ref))
ref.Close()
}
// Close manually closes the image and frees the memory. Calling Close() is optional.
// Images are automatically closed by GC. However, in high volume applications the GC
// can't keep up with the amount of memory, so you might want to manually close the images.
func (r *ImageRef) Close() {
r.lock.Lock()
if r.image != nil {
clearImage(r.image)
r.image = nil
}
r.buf = nil
r.lock.Unlock()
}
// Format returns the current format of the vips image.
func (r *ImageRef) Format() ImageType {
return r.format
}
// OriginalFormat returns the original format of the image when loaded.
// In some cases the loaded image is converted on load, for example, a BMP is automatically converted to PNG
// This method returns the format of the original buffer, as opposed to Format() with will return the format of the
// currently held buffer content.
func (r *ImageRef) OriginalFormat() ImageType {
return r.originalFormat
}
// Width returns the width of this image.
func (r *ImageRef) Width() int {
return int(r.image.Xsize)
}
// Height returns the height of this image.
func (r *ImageRef) Height() int {
return int(r.image.Ysize)
}
// Bands returns the number of bands for this image.
func (r *ImageRef) Bands() int {
return int(r.image.Bands)
}
// HasProfile returns if the image has an ICC profile embedded.
func (r *ImageRef) HasProfile() bool {
return vipsHasICCProfile(r.image)
}
// HasICCProfile checks whether the image has an ICC profile embedded. Alias to HasProfile
func (r *ImageRef) HasICCProfile() bool {
return r.HasProfile()
}
// HasIPTC returns a boolean whether the image in question has IPTC data associated with it.
func (r *ImageRef) HasIPTC() bool {
return vipsHasIPTC(r.image)
}
// HasAlpha returns if the image has an alpha layer.
func (r *ImageRef) HasAlpha() bool {
return vipsHasAlpha(r.image)
}
// Orientation returns the orientation number as it appears in the EXIF, if present
func (r *ImageRef) Orientation() int {
return vipsGetMetaOrientation(r.image)
}
// Deprecated: use Orientation() instead
func (r *ImageRef) GetOrientation() int {
return r.Orientation()
}
// SetOrientation sets the orientation in the EXIF header of the associated image.
func (r *ImageRef) SetOrientation(orientation int) error {
out, err := vipsCopyImage(r.image)
if err != nil {
return err
}
vipsSetMetaOrientation(out, orientation)
r.setImage(out)
return nil
}
// RemoveOrientation removes the EXIF orientation information of the image.
func (r *ImageRef) RemoveOrientation() error {
out, err := vipsCopyImage(r.image)
if err != nil {
return err
}
vipsRemoveMetaOrientation(out)
r.setImage(out)
return nil
}
// ResX returns the X resolution
func (r *ImageRef) ResX() float64 {
return float64(r.image.Xres)
}
// ResY returns the Y resolution
func (r *ImageRef) ResY() float64 {
return float64(r.image.Yres)
}
// OffsetX returns the X offset
func (r *ImageRef) OffsetX() int {
return int(r.image.Xoffset)
}
// OffsetY returns the Y offset
func (r *ImageRef) OffsetY() int {
return int(r.image.Yoffset)
}
// BandFormat returns the current band format
func (r *ImageRef) BandFormat() BandFormat {
return BandFormat(int(r.image.BandFmt))
}
// Coding returns the image coding
func (r *ImageRef) Coding() Coding {
return Coding(int(r.image.Coding))
}
// Interpretation returns the current interpretation of the color space of the image.
func (r *ImageRef) Interpretation() Interpretation {
return Interpretation(int(r.image.Type))
}
// ColorSpace returns the interpretation of the current color space. Alias to Interpretation().
func (r *ImageRef) ColorSpace() Interpretation {
return r.Interpretation()
}
// IsColorSpaceSupported returns a boolean whether the image's color space is supported by libvips.
func (r *ImageRef) IsColorSpaceSupported() bool {
return vipsIsColorSpaceSupported(r.image)
}
// Pages returns the number of pages in the Image
// For animated images this corresponds to the number of frames
func (r *ImageRef) 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)
}
// Deprecated: use Pages() instead
func (r *ImageRef) GetPages() int {
return r.Pages()
}
// SetPages sets the number of pages in the Image
// For animated images this corresponds to the number of frames
func (r *ImageRef) SetPages(pages int) error {
out, err := vipsCopyImage(r.image)
if err != nil {
return err
}
vipsSetImageNPages(r.image, pages)
r.setImage(out)
return nil
}
// PageHeight return the height of a single page
func (r *ImageRef) PageHeight() int {
return vipsGetPageHeight(r.image)
}
// GetPageHeight return the height of a single page
// Deprecated use PageHeight() instead
func (r *ImageRef) GetPageHeight() int {
return vipsGetPageHeight(r.image)
}
// SetPageHeight set the height of a page
// For animated images this is used when "unrolling" back to frames
func (r *ImageRef) SetPageHeight(height int) error {
out, err := vipsCopyImage(r.image)
if err != nil {
return err
}
vipsSetPageHeight(out, height)
r.setImage(out)
return nil
}
// PageDelay get the page delay array for animation
func (r *ImageRef) PageDelay() ([]int, error) {
n := vipsGetImageNPages(r.image)
if n <= 1 {
// should not call if not multi page
return nil, nil
}
return vipsImageGetDelay(r.image, n)
}
// SetPageDelay set the page delay array for animation
func (r *ImageRef) SetPageDelay(delay []int) error {
var data []C.int
for _, d := range delay {
data = append(data, C.int(d))
}
return vipsImageSetDelay(r.image, data)
}
// Export creates a byte array of the image for use.
// The function returns a byte array that can be written to a file e.g. via ioutil.WriteFile().
// N.B. govips does not currently have built-in support for directly exporting to a file.
// The function also returns a copy of the image metadata as well as an error.
// Deprecated: Use ExportNative or format-specific Export methods
func (r *ImageRef) Export(params *ExportParams) ([]byte, *ImageMetadata, error) {
if params == nil || params.Format == ImageTypeUnknown {
return r.ExportNative()
}
format := params.Format
if !IsTypeSupported(format) {
return nil, r.newMetadata(ImageTypeUnknown), fmt.Errorf("cannot save to %#v", ImageTypes[format])
}
switch format {
case ImageTypeGIF:
return r.ExportGIF(&GifExportParams{
Quality: params.Quality,
})
case ImageTypeWEBP:
return r.ExportWebp(&WebpExportParams{
StripMetadata: params.StripMetadata,
Quality: params.Quality,
Lossless: params.Lossless,
ReductionEffort: params.Effort,
})
case ImageTypePNG:
return r.ExportPng(&PngExportParams{
StripMetadata: params.StripMetadata,
Compression: params.Compression,
Interlace: params.Interlaced,
})
case ImageTypeTIFF:
compression := TiffCompressionLzw
if params.Lossless {
compression = TiffCompressionNone
}
return r.ExportTiff(&TiffExportParams{
StripMetadata: params.StripMetadata,
Quality: params.Quality,
Compression: compression,
})
case ImageTypeHEIF:
return r.ExportHeif(&HeifExportParams{
Quality: params.Quality,
Lossless: params.Lossless,
})
case ImageTypeAVIF:
return r.ExportAvif(&AvifExportParams{
StripMetadata: params.StripMetadata,
Quality: params.Quality,
Lossless: params.Lossless,
Speed: params.Speed,
})
default:
format = ImageTypeJPEG
return r.ExportJpeg(&JpegExportParams{
Quality: params.Quality,
StripMetadata: params.StripMetadata,
Interlace: params.Interlaced,
OptimizeCoding: params.OptimizeCoding,
SubsampleMode: params.SubsampleMode,
TrellisQuant: params.TrellisQuant,
OvershootDeringing: params.OvershootDeringing,
OptimizeScans: params.OptimizeScans,
QuantTable: params.QuantTable,
})
}
}
// ExportNative exports the image to a buffer based on its native format with default parameters.
func (r *ImageRef) ExportNative() ([]byte, *ImageMetadata, error) {
switch r.format {
case ImageTypeJPEG:
return r.ExportJpeg(NewJpegExportParams())
case ImageTypePNG:
return r.ExportPng(NewPngExportParams())
case ImageTypeWEBP:
return r.ExportWebp(NewWebpExportParams())
case ImageTypeHEIF:
return r.ExportHeif(NewHeifExportParams())
case ImageTypeTIFF:
return r.ExportTiff(NewTiffExportParams())
case ImageTypeAVIF:
return r.ExportAvif(NewAvifExportParams())
case ImageTypeJP2K:
return r.ExportJp2k(NewJp2kExportParams())
case ImageTypeGIF:
return r.ExportGIF(NewGifExportParams())
default:
return r.ExportJpeg(NewJpegExportParams())
}
}
// ExportJpeg exports the image as JPEG to a buffer.
func (r *ImageRef) ExportJpeg(params *JpegExportParams) ([]byte, *ImageMetadata, error) {
if params == nil {
params = NewJpegExportParams()
}
buf, err := vipsSaveJPEGToBuffer(r.image, *params)
if err != nil {
return nil, nil, err
}
return buf, r.newMetadata(ImageTypeJPEG), nil
}
// ExportPng exports the image as PNG to a buffer.
func (r *ImageRef) ExportPng(params *PngExportParams) ([]byte, *ImageMetadata, error) {
if params == nil {
params = NewPngExportParams()
}
buf, err := vipsSavePNGToBuffer(r.image, *params)
if err != nil {
return nil, nil, err
}
return buf, r.newMetadata(ImageTypePNG), nil
}
// ExportWebp exports the image as WEBP to a buffer.
func (r *ImageRef) ExportWebp(params *WebpExportParams) ([]byte, *ImageMetadata, error) {
if params == nil {
params = NewWebpExportParams()
}
paramsWithIccProfile := *params
paramsWithIccProfile.IccProfile = r.optimizedIccProfile
buf, err := vipsSaveWebPToBuffer(r.image, paramsWithIccProfile)
if err != nil {
return nil, nil, err
}
return buf, r.newMetadata(ImageTypeWEBP), nil
}
// ExportHeif exports the image as HEIF to a buffer.
func (r *ImageRef) ExportHeif(params *HeifExportParams) ([]byte, *ImageMetadata, error) {
if params == nil {
params = NewHeifExportParams()
}
buf, err := vipsSaveHEIFToBuffer(r.image, *params)
if err != nil {
return nil, nil, err
}
return buf, r.newMetadata(ImageTypeHEIF), nil
}
// ExportTiff exports the image as TIFF to a buffer.
func (r *ImageRef) ExportTiff(params *TiffExportParams) ([]byte, *ImageMetadata, error) {
if params == nil {
params = NewTiffExportParams()
}
buf, err := vipsSaveTIFFToBuffer(r.image, *params)
if err != nil {
return nil, nil, err
}
return buf, r.newMetadata(ImageTypeTIFF), nil
}
// ExportGIF exports the image as GIF to a buffer.
func (r *ImageRef) ExportGIF(params *GifExportParams) ([]byte, *ImageMetadata, error) {
if params == nil {
params = NewGifExportParams()
}