-
Notifications
You must be signed in to change notification settings - Fork 50
/
vimage.py
1930 lines (1446 loc) · 60.6 KB
/
vimage.py
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
# wrap VipsImage
from __future__ import division
import numbers
import struct
import pyvips
from pyvips import ffi, glib_lib, vips_lib, Error, _to_bytes, \
_to_string, _to_string_copy, GValue, at_least_libvips, Introspect
# either a single number, or a table of numbers
def _is_pixel(value):
return (isinstance(value, numbers.Number) or
(isinstance(value, list) and not
isinstance(value, pyvips.Image)))
# test for rectangular array of something
def _is_2D(array):
if not isinstance(array, list):
return False
for x in array:
if not isinstance(x, list):
return False
if len(x) != len(array[0]):
return False
return True
# apply a function to a thing, or map over a list
# we often need to do something like (1.0 / other) and need to work for lists
# as well as scalars
def _smap(func, x):
if isinstance(x, list):
return list(map(func, x))
else:
return func(x)
def _call_enum(image, other, base, operation):
if _is_pixel(other):
return pyvips.Operation.call(base + '_const', image, operation, other)
else:
return pyvips.Operation.call(base, image, other, operation)
def _run_cmplx(fn, image):
"""Run a complex function on a non-complex image.
The image needs to be complex, or have an even number of bands. The input
can be int, the output is always float or double.
"""
original_format = image.format
if image.format != 'complex' and image.format != 'dpcomplex':
if image.bands % 2 != 0:
raise Error('not an even number of bands')
if image.format != 'float' and image.format != 'double':
image = image.cast('float')
if image.format == 'double':
new_format = 'dpcomplex'
else:
new_format = 'complex'
image = image.copy(format=new_format, bands=image.bands / 2)
image = fn(image)
if original_format != 'complex' and original_format != 'dpcomplex':
if image.format == 'dpcomplex':
new_format = 'double'
else:
new_format = 'float'
image = image.copy(format=new_format, bands=image.bands * 2)
return image
# https://stackoverflow.com/a/22409540/1480019
# https://github.com/benjaminp/six/blob/33b584b2c551548021adb92a028ceaf892deb5be/six.py#L846-L861
def _with_metaclass(metaclass):
"""Class decorator for creating a class with a metaclass."""
def wrapper(cls):
orig_vars = cls.__dict__.copy()
slots = orig_vars.get('__slots__')
if slots is not None:
if isinstance(slots, str):
slots = [slots]
for slots_var in slots:
orig_vars.pop(slots_var)
orig_vars.pop('__dict__', None)
orig_vars.pop('__weakref__', None)
if hasattr(cls, '__qualname__'):
orig_vars['__qualname__'] = cls.__qualname__
return metaclass(cls.__name__, cls.__bases__, orig_vars)
return wrapper
# decorator to set docstring
def _add_doc(name):
try:
docstring = pyvips.Operation.generate_docstring(name)
except Error:
docstring = None
def _doc(func):
func.__doc__ = docstring
return func
return _doc
# decorator to set deprecated
def _deprecated(note):
def _dep(func):
func.__deprecated__ = note
return func
return _dep
# Rules for the mapping between numpy typestrings and libvips formats
# b1: bool. Above u1 so that rev. map is uchar->u1
TYPESTR_TO_FORMAT = {'|b1': 'uchar',
'|u1': 'uchar',
'|i1': 'char',
'<u2': 'ushort',
'<i2': 'short',
'<u4': 'uint',
'<i4': 'int',
'<f4': 'float',
'<c8': 'complex',
'<f8': 'double',
'<c16': 'dpcomplex'}
# Rules for the mapping between libvips formats and numpy typestrings
FORMAT_TO_TYPESTR = dict((v, k) for k, v in TYPESTR_TO_FORMAT.items())
# see https://docs.python.org/3/library/struct.html
FORMAT_TO_PYFORMAT = {'uchar': 'B',
'char': 'c',
'ushort': 'H',
'short': 'h',
'uint': 'I',
'int': 'i',
'float': 'f',
'double': 'd',
'complex': 'f', # n.b. no support for complex in C
'dpcomplex': 'd'}
def _guess_interpretation(bands, format):
"""Return a best-guess interpretation string based on bands and libvips
format.
Args:
bands (int): Number of bands in the image.
format (str): libvips format string.
Returns:
str: the best-guess libvips interpretation string.
This function is a helper for :class:`.Image` creation from arrays when the
user specifies 'auto' for `interpretation`.
The heuristic used here can be defined in the following table::
| bands | format | interpretation | reason |
| ----- | --------- | -------------- | ------------ |
| 1 | uchar | b-w | L |
| 2 | uchar | b-w | LA |
| 3 | uchar | rgb | RGB |
| 4 | uchar | rgb | RGBA |
| 5+ | uchar | multiband | spectral |
| 1 | char | matrix | conv. kernel |
| 2+ | char | multiband | |
| 1 | ushort | grey16 | L |
| 2 | ushort | grey16 | LA |
| 3 | ushort | rgb16 | RGB |
| 4 | ushort | rgb16 | RGBA |
| 5+ | ushort | multiband | spectral |
| any | short | multiband | |
| 1 | float | b-w | L |
| 2 | float | b-w | LA |
| 3 | float | scrgb | RGB |
| 4 | float | scrgb | RGBA |
| 5+ | float | multiband | spectral |
| 1 | double | b-w | L |
| 2 | double | b-w | LA |
| 3 | double | scrgb | RGB |
| 4 | double | scrgb | RGBA |
| 5+ | double | multiband | spectral |
| any | complex | fourier | FFT |
| any | dpcomplex | fourier | FFT |
"""
if format not in FORMAT_TO_TYPESTR:
raise ValueError('Unknown format: {}'.format(format))
if not isinstance(bands, int) or bands < 1:
raise ValueError('Number of bands must be a positive integer.')
# the default
interp = 'multiband'
if format == 'uchar':
if bands in [1, 2]:
interp = 'b-w'
elif bands in [3, 4]:
interp = 'rgb'
elif format == 'char':
if bands == 1:
interp = 'matrix'
elif format == 'ushort':
if bands in [1, 2]:
interp = 'grey16'
elif bands in [3, 4]:
interp = 'rgb16'
elif format == 'short':
if bands == 1:
interp = 'matrix'
elif format in ['float', 'double']:
if bands in [1, 2]:
interp = 'b-w'
elif bands in [3, 4]:
interp = 'scrgb'
elif format in ['complex', 'dpcomplex']:
interp = 'fourier'
return interp
# metaclass for Image ... getattr on this implements the class methods
class ImageType(type):
def __getattr__(cls, name):
# logger.debug('ImageType.__getattr__ %s', name)
# does the method exist in libvips?
try:
# this will throw an exception if not
Introspect.get(name)
except Error:
# we need to throw this exception for missing methods, eg. numpy
# checks for this
raise AttributeError
@_add_doc(name)
def call_function(*args, **kwargs):
return pyvips.Operation.call(name, *args, **kwargs)
return call_function
@_with_metaclass(ImageType)
class Image(pyvips.VipsObject):
"""Wrap a VipsImage object.
"""
__slots__ = ('_references',)
# private static
@staticmethod
def _imageize(self, value):
# careful! self can be None if value is a 2D array
if isinstance(value, Image):
return value
elif _is_2D(value):
return Image.new_from_array(value)
else:
return self.new_from_image(value)
def __init__(self, pointer):
# a list of other objects which this object depends on and which need
# to be kept alive
# we can't use a set because set elements are unique under "==", and
# Python checks memoryview equality with hash functions, not pointer
# equality
self._references = []
# logger.debug('Image.__init__: pointer = %s', pointer)
super(Image, self).__init__(pointer)
# constructors
@staticmethod
def new_from_file(vips_filename, **kwargs):
"""Load an image from a file.
This method can load images in any format supported by vips. The
filename can include load options, for example::
image = pyvips.Image.new_from_file('fred.jpg[shrink=2]')
You can also supply options as keyword arguments, for example::
image = pyvips.Image.new_from_file('fred.jpg', shrink=2)
The full set of options available depend upon the load operation that
will be executed. Try something like::
$ vips jpegload
at the command-line to see a summary of the available options for the
JPEG loader.
Loading is fast: only enough of the image is loaded to be able to fill
out the header. Pixels will only be decompressed when they are needed.
Args:
vips_filename (str): The disc file to load the image from, with
optional appended arguments.
All loaders support at least the following options:
Keyword args:
memory (bool): If set True, load the image via memory rather than
via a temporary disc file. See :meth:`.new_temp_file` for
notes on where temporary files are created. Small images are
loaded via memory by default, use ``VIPS_DISC_THRESHOLD`` to
set the definition of small.
access (Access): Hint the expected access pattern for the image.
fail (bool): If set True, the loader will fail with an error on
the first serious error in the file. By default, libvips
will attempt to read everything it can from a damaged image.
Returns:
A new :class:`.Image`.
Raises:
:class:`.Error`
"""
vips_filename = _to_bytes(vips_filename)
pointer = vips_lib.vips_filename_get_filename(vips_filename)
filename = _to_string_copy(pointer)
pointer = vips_lib.vips_filename_get_options(vips_filename)
options = _to_string_copy(pointer)
pointer = vips_lib.vips_foreign_find_load(vips_filename)
if pointer == ffi.NULL:
raise Error('unable to load from file {0}'.format(vips_filename))
name = _to_string(pointer)
return pyvips.Operation.call(name, filename,
string_options=options, **kwargs)
@staticmethod
def new_from_buffer(data, options, **kwargs):
"""Load a formatted image from memory.
This behaves exactly as :meth:`new_from_file`, but the image is
loaded from the memory object rather than from a file. The memory
object can be anything that supports the Python buffer protocol.
Args:
data (array, bytearray, bytes, buffer): The memory object to
load the image from.
options (str): Load options as a string. Use ``""`` for no options.
All loaders support at least the following options:
Keyword args:
access (Access): Hint the expected access pattern for the image.
fail (bool): If set True, the loader will fail with an error on the
first serious error in the image. By default, libvips will
attempt to read everything it can from a damaged image.
Returns:
A new :class:`Image`.
Raises:
:class:`.Error`
"""
pointer = vips_lib.vips_foreign_find_load_buffer(data, len(data))
if pointer == ffi.NULL:
raise Error('unable to load from buffer')
name = _to_string(pointer)
return pyvips.Operation.call(name, data,
string_options=options, **kwargs)
@staticmethod
def new_from_list(array, scale=1.0, offset=0.0):
"""Create an image from a list or list of lists.
A new one-band image with :class:`BandFormat` ``'double'`` pixels is
created from the array. These image are useful with the libvips
convolution operator :meth:`Image.conv`.
Args:
array (list[list[float]]): Create the image from these values.
1D arrays become a single row of pixels.
scale (float): Default to 1.0. What to divide each pixel by after
convolution. Useful for integer convolution masks.
offset (float): Default to 0.0. What to subtract from each pixel
after convolution. Useful for integer convolution masks.
Returns:
A new :class:`Image`.
Raises:
:class:`.Error`
"""
if not _is_2D(array):
array = [array]
height = len(array)
width = len(array[0])
n = width * height
a = ffi.new('double[]', n)
for y in range(0, height):
for x in range(0, width):
a[x + y * width] = array[y][x]
vi = vips_lib.vips_image_new_matrix_from_array(width, height, a, n)
if vi == ffi.NULL:
raise Error('unable to make image from matrix')
image = pyvips.Image(vi)
image.set_type(GValue.gdouble_type, 'scale', scale)
image.set_type(GValue.gdouble_type, 'offset', offset)
return image
@classmethod
def new_from_array(cls, obj, scale=1.0, offset=0.0, interpretation=None):
"""Create a new Image from a list or an array-like object.
Array-like objects are those which define `__array_interface__` or
`__array__`. For details about the array interface, see `The Array
Interface
<https://numpy.org/doc/stable/reference/arrays.interface.html>`_.
If `__array_interface__` is not available, `__array__` is used as a
fallback.
The behavior for input objects with different dimensions is summarized
as::
| array ndim | array shape | Image w | Image h | Image bands |
|------------|-------------|---------|---------|-------------|
| 0 | () | 1 | 1 | 1 |
| 1 | (W,) | W | 1 | 1 |
| 2 | (H, W) | W | H | 1 |
| 3 | (H, W, C) | W | H | C |
Args:
obj (list or object width `__array_interface__` or `__array__`):
The object to convert to an image.
If the input object is a list, `Image.new_from_list` is used
with the given `scale` and `offset`
If the input object is an array-like object, a new image is
created from the object's data and shape. The memory is shared
except in the following cases:
- The object's memory is not contiguous. In this case, a copy
is made by attempting to call the object's `tobytes()` method
or its `tostring()` method.
- The object is an array of bools, in which case it is
converted to a pyvips uchar image with True values becoming
255 and False values becoming 0.
scale (float): Default to 1.0. **Ignored for non-list inputs**.
What to divide each pixel by after convolution. Useful for
integer convolution masks.
offset (float): Default to 0.0. **Ignored for non-list inputs**.
What to subtract from each pixel after convolution. Useful for
integer convolution masks.
interpretation (str, optional): **Ignored for list inputs** The
libvips interpretation of the array. If None, the
interpretation defaults to the pyvips one for
`Image.new_from_memory`.
If 'auto', a heuristic is used to determine a best-guess
interpretation as defined in the `_guess_interpretation`
function.
Must be one of None, 'auto', 'error', 'multiband', 'b-w',
'histogram', 'xyz', 'lab', 'cmyk', 'labq', 'rgb', 'cmc', 'lch',
'labs', 'srgb', 'yxy', 'fourier', 'rgb16', 'grey16', 'matrix',
'scrgb', or 'hsv'
Returns:
The new image.
See Also:
:func:`_guess_interpretation`
"""
if isinstance(obj, list):
return cls.new_from_list(obj, scale, offset)
if hasattr(obj, '__array_interface__'):
a = obj.__array_interface__
shape = a['shape']
typestr = a['typestr']
ndim = len(shape)
# strides is optional
strides = a.get('strides', None)
if ndim > 3:
raise ValueError('array has more than 3 dimensions')
if typestr not in TYPESTR_TO_FORMAT:
raise ValueError('conversion from {0} not supported'
.format(typestr))
if ndim == 0:
width = 1
height = 1
bands = 1
elif ndim == 1:
width = shape[0]
height = 1
bands = 1
elif ndim == 2:
height, width = shape
bands = 1
elif ndim == 3:
height, width, bands = shape
format = TYPESTR_TO_FORMAT[typestr]
if strides is None and hasattr(obj, 'data'):
data = obj.data
else:
# To obtain something with a contiguous memory layout
if hasattr(obj, 'tobytes'):
data = obj.tobytes()
elif hasattr(obj, 'tostring'):
data = obj.tostring()
else:
raise TypeError('object has no .tobytes or .tostring')
im = cls.new_from_memory(
data,
width,
height,
bands,
format
)
if typestr == '|b1':
# special case for bool: true in vips is uchar(255)
im = im.ifthenelse(255, 0)
if interpretation is not None:
if interpretation == 'auto':
interpretation = _guess_interpretation(bands, format)
im = im.copy(interpretation=interpretation)
return im
elif hasattr(obj, '__array__'):
# make it into something that *does* define __array_interface__
return cls.new_from_array(obj.__array__())
else:
raise TypeError('does not define __array_interface__ '
'or __array__')
@staticmethod
def new_from_memory(data, width, height, bands, format):
"""Wrap an image around a memory array.
Wraps an Image around an area of memory containing a C-style array. For
example, if the ``data`` memory array contains four bytes with the
values 1, 2, 3, 4, you can make a one-band, 2x2 uchar image from
it like this::
image = Image.new_from_memory(data, 2, 2, 1, 'uchar')
A reference is kept to the data object, so it will not be
garbage-collected until the returned image is garbage-collected.
This method is useful for efficiently transferring images from PIL or
NumPy into libvips.
See :meth:`.write_to_memory` for the opposite operation.
Use :meth:`.copy` to set other image attributes.
Args:
data (bytes): A memoryview or buffer object.
width (int): Image width in pixels.
height (int): Image height in pixels.
bands (int): Number of bands.
format (BandFormat): Band format.
Returns:
A new :class:`Image`.
Raises:
:class:`.Error`
"""
format_value = GValue.to_enum(GValue.format_type, format)
pointer = ffi.from_buffer(data)
# py3:
# - memoryview has .nbytes for number of bytes in object
# - len() returns number of elements in top array
# py2:
# - buffer has no nbytes member
# - but len() gives number of bytes in object
nbytes = data.nbytes if hasattr(data, 'nbytes') else len(data)
vi = vips_lib.vips_image_new_from_memory(pointer,
nbytes,
width, height, bands,
format_value)
if vi == ffi.NULL:
raise Error('unable to make image from memory')
image = pyvips.Image(vi)
# keep a secret ref to the underlying object .. this reference will be
# inherited by things that in turn depend on us, so the memory we are
# using will not be freed
image._references.append(data)
return image
@staticmethod
def new_from_source(source, options, **kwargs):
"""Load a formatted image from a source.
This behaves exactly as :meth:`new_from_file`, but the image is
loaded from the source rather than from a file.
Args:
source (Source): The source to load the image from.
options (str): Load options as a string. Use ``""`` for no options.
All loaders support at least the following options:
Keyword args:
access (Access): Hint the expected access pattern for the image.
fail (bool): If set True, the loader will fail with an error on the
first serious error in the image. By default, libvips will
attempt to read everything it can from a damaged image.
Returns:
A new :class:`Image`.
Raises:
:class:`.Error`
"""
pointer = vips_lib.vips_foreign_find_load_source(source.pointer)
if pointer == ffi.NULL:
raise Error('unable to load from source')
name = _to_string(pointer)
image = pyvips.Operation.call(name, source,
string_options=options, **kwargs)
# keep a secret ref to the source object .. we need that to stay
# alive, since it might be a custom source that triggers a python
# callback
image._references.append(source)
return image
@staticmethod
def new_temp_file(format):
"""Make a new temporary image.
Returns an image backed by a temporary file. When written to with
:func:`Image.write`, a temporary file will be created on disc in the
specified format. When the image is closed, the file will be deleted
automatically.
The file is created in the temporary directory. This is set with
the environment variable ``TMPDIR``. If this is not set, then on
Unix systems, vips will default to ``/tmp``. On Windows, vips uses
``GetTempPath()`` to find the temporary directory.
vips uses ``g_mkstemp()`` to make the temporary filename. They
generally look something like ``"vips-12-EJKJFGH.v"``.
Args:
format (str): The format for the temp file, for example
``"%s.v"`` for a vips format file. The ``%s`` is
substituted by the file path.
Returns:
A new :class:`Image`.
Raises:
:class:`.Error`
"""
vi = vips_lib.vips_image_new_temp_file(_to_bytes(format))
if vi == ffi.NULL:
raise Error('unable to make temp file')
return pyvips.Image(vi)
def new_from_image(self, value):
"""Make a new image from an existing one.
A new image is created which has the same size, format, interpretation
and resolution as ``self``, but with every pixel set to ``value``.
Args:
value (float, list[float]): The value for the pixels. Use a
single number to make a one-band image; use an array constant
to make a many-band image.
Returns:
A new :class:`Image`.
Raises:
:class:`.Error`
"""
pixel = (Image.black(1, 1) + value).cast(self.format)
image = pixel.embed(0, 0, self.width, self.height,
extend='copy')
image = image.copy(interpretation=self.interpretation,
xres=self.xres,
yres=self.yres,
xoffset=self.xoffset,
yoffset=self.yoffset)
return image
def copy_memory(self):
"""Copy an image to memory.
A large area of memory is allocated, the image is rendered to that
memory area, and a new image is returned which wraps that large memory
area.
Returns:
A new :class:`Image`.
Raises:
:class:`.Error`
"""
vi = vips_lib.vips_image_copy_memory(self.pointer)
if vi == ffi.NULL:
raise Error('unable to copy to memory')
return pyvips.Image(vi)
# writers
def write_to_file(self, vips_filename, **kwargs):
"""Write an image to a file on disc.
This method can save images in any format supported by vips. The format
is selected from the filename suffix. The filename can include embedded
save options, see :func:`Image.new_from_file`.
For example::
image.write_to_file('fred.jpg[Q=95]')
You can also supply options as keyword arguments, for example::
image.write_to_file('fred.jpg', Q=95)
The full set of options available depend upon the load operation that
will be executed. Try something like::
$ vips jpegsave
at the command-line to see a summary of the available options for the
JPEG saver.
Args:
vips_filename (str): The disc file to save the image to, with
optional appended arguments.
Other arguments depend upon the save operation.
Returns:
None
Raises:
:class:`.Error`
"""
vips_filename = _to_bytes(vips_filename)
pointer = vips_lib.vips_filename_get_filename(vips_filename)
filename = _to_string_copy(pointer)
pointer = vips_lib.vips_filename_get_options(vips_filename)
options = _to_string_copy(pointer)
pointer = vips_lib.vips_foreign_find_save(vips_filename)
if pointer == ffi.NULL:
raise Error('unable to write to file {0}'.format(vips_filename))
name = _to_string(pointer)
return pyvips.Operation.call(name, self, filename,
string_options=options, **kwargs)
def write_to_buffer(self, format_string, **kwargs):
"""Write an image to memory.
This method can save images in any format supported by vips. The format
is selected from the suffix in the format string. This can include
embedded save options, see :func:`Image.write_to_file`.
For example::
data = image.write_to_buffer('.jpg[Q=95]')
You can also supply options as keyword arguments, for example::
data = image.write_to_buffer('.jpg', Q=95)
The full set of options available depend upon the load operation that
will be executed. Try something like::
$ vips jpegsave_buffer
at the command-line to see a summary of the available options for the
JPEG saver.
Args:
format_string (str): The suffix, plus any string-form arguments.
Other arguments depend upon the save operation.
Returns:
A byte string.
Raises:
:class:`.Error`
"""
format_string = _to_bytes(format_string)
filename = vips_lib.vips_filename_get_filename(format_string)
pointer = vips_lib.vips_filename_get_options(format_string)
options = _to_string_copy(pointer)
pointer = ffi.NULL
if at_least_libvips(8, 9):
vips_lib.vips_error_freeze()
pointer = vips_lib.vips_foreign_find_save_target(filename)
vips_lib.vips_error_thaw()
if pointer != ffi.NULL:
name = _to_string(pointer)
target = pyvips.Target.new_to_memory()
pyvips.Operation.call(name, self, target,
string_options=options, **kwargs)
buffer = target.get("blob")
else:
pointer = vips_lib.vips_foreign_find_save_buffer(filename)
if pointer == ffi.NULL:
raise Error('unable to write to buffer')
name = _to_string(pointer)
buffer = pyvips.Operation.call(name, self,
string_options=options, **kwargs)
return buffer
def write_to_target(self, target, format_string, **kwargs):
"""Write an image to a target.
This method will write the image to the target in the format
specified in the suffix in the format string. This can include
embedded save options, see :func:`Image.write_to_file`.
For example::
image.write_to_target(target, '.jpg[Q=95]')
You can also supply options as keyword arguments, for example::
image.write_to_target(target, '.jpg', Q=95)
The full set of options available depend upon the save operation that
will be executed. Try something like::
$ vips jpegsave_target
at the command-line to see a summary of the available options for the
JPEG saver.
Args:
target (Target): The target to write the image to
format_string (str): The suffix, plus any string-form arguments.
Other arguments depend upon the save operation.
Returns:
None
Raises:
:class:`.Error`
"""
format_string = _to_bytes(format_string)
pointer = vips_lib.vips_filename_get_options(format_string)
options = _to_string_copy(pointer)
pointer = vips_lib.vips_foreign_find_save_target(format_string)
if pointer == ffi.NULL:
raise Error('unable to write to target')
name = _to_string(pointer)
return pyvips.Operation.call(name, self, target,
string_options=options, **kwargs)
def write_to_memory(self):
"""Write the image to a large memory array.
A large area of memory is allocated, the image is rendered to that
memory array, and the array is returned as a buffer.
For example, if you have a 2x2 uchar image containing the bytes 1, 2,
3, 4, read left-to-right, top-to-bottom, then::
buf = image.write_to_memory()
will return a four byte buffer containing the values 1, 2, 3, 4.
Returns:
buffer
Raises:
:class:`.Error`
"""
psize = ffi.new('size_t *')
pointer = vips_lib.vips_image_write_to_memory(self.pointer, psize)
if pointer == ffi.NULL:
raise Error('unable to write to memory')
pointer = ffi.gc(pointer, glib_lib.g_free)
return ffi.buffer(pointer, psize[0])
def write(self, other):
"""Write an image to another image.
This function writes ``self`` to another image. Use something like
:func:`Image.new_temp_file` to make an image that can be written to.
Args:
other (Image): The :class:`Image` to write to,
Returns:
None
Raises:
:class:`.Error`
"""
result = vips_lib.vips_image_write(self.pointer, other.pointer)
if result != 0:
raise Error('unable to write to image')
def invalidate(self):
"""Drop caches on an image, and any downstream images.
This method drops all pixel caches on an image and on all downstream
images. Any operations which depend on this image, directly or
indirectly, are also dropped from the libvips operation cache.
This method can be useful if you wrap a libvips image around an area
of memory with :meth:`.new_from_memory` and then change some bytes
without libvips knowing.
Returns:
None
"""
vips_lib.vips_image_invalidate_all(self.pointer)
def set_progress(self, progress):
"""Enable progress reporting on an image.
When progress reporting is enabled, evaluation of the most downstream
image from this image will report progress using the ::preeval, ::eval,
and ::posteval signals.
"""