-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathImage.php
2492 lines (2317 loc) · 68.3 KB
/
Image.php
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
<?php
/**
* Vips is a php binding for the vips image processing library
*
* PHP version 7
*
* LICENSE:
*
* Copyright (c) 2016 John Cupitt
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* @category Images
* @package Jcupitt\Vips
* @author John Cupitt <[email protected]>
* @copyright 2016 John Cupitt
* @license https://opensource.org/licenses/MIT MIT
* @link https://github.com/jcupitt/php-vips
*/
namespace Jcupitt\Vips;
/**
* This class represents a Vips image object.
*
* This module provides a binding for the [vips image processing
* library](https://libvips.org) version 8.7 and later, and requires PHP 7.4
* and later.
*
* # Example
*
* ```php
* <?php
* use Jcupitt\Vips;
* $im = Vips\Image::newFromFile($argv[1], ['access' => 'sequential']);
* $im = $im->crop(100, 100, $im->width - 200, $im->height - 200);
* $im = $im->reduce(1.0 / 0.9, 1.0 / 0.9, ['kernel' => 'linear']);
* $mask = Vips\Image::newFromArray(
* [[-1, -1, -1],
* [-1, 16, -1],
* [-1, -1, -1]], 8);
* $im = $im->conv($mask);
* $im->writeToFile($argv[2]);
* ?>
* ```
*
* You'll need this in your `composer.json`:
*
* ```
* "require": {
* "jcupitt/vips" : "2.0.0"
* }
* ```
*
* And run with:
*
* ```
* $ composer install
* $ ./try1.php ~/pics/k2.jpg x.tif
* ```
*
* This example loads a file, crops 100 pixels from every edge, reduces by 10%
* using a bilinear interpolator (the default is lanczos3),
* sharpens the image, and saves it back to disc again.
*
* Reading this example line by line, we have:
*
* ```php
* $im = Vips\Image::newFromFile($argv[1], ['access' => 'sequential']);
* ```
*
* `Image::newFromFile` can load any image file supported by vips. Almost all
* operations can be given an array of options as a final argument.
*
* In this
* example, we will be accessing pixels top-to-bottom as we sweep through the
* image reading and writing, so `sequential` access mode is best for us. The
* default mode is `random`, this allows for full random access to image pixels,
* but is slower and needs more memory.
*
* You can also load formatted images from strings or create images from
* PHP arrays.
*
* See the [main libvips
* documentation](https://www.libvips.org/API/current/VipsImage.html#vips-image-new-from-file)
* for a more detailed explaination.
*
* The next line:
*
* ```php
* $im = $im->crop(100, 100, $im->width - 200, $im->height - 200);
* ```
*
* Crops 100 pixels from every edge. You can access any vips image property
* directly as a PHP property. If the vips property name does not
* conform to PHP naming conventions, you can use something like
* `$image->get('ipct-data')`.
*
* Use `$image->getFields()` to get an array of all the possible field names.
*
* Next we have:
*
* ```php
* $mask = Vips\Image::newFromArray(
* [[-1, -1, -1],
* [-1, 16, -1],
* [-1, -1, -1]], 8);
* $im = $im->conv($mask);
* ```
*
* `Image::newFromArray` creates an image from an array constant. The 8 at
* the end sets the scale: the amount to divide the image by after
* integer convolution. See the libvips API docs for `vips_conv()` (the operation
* invoked by `Image::conv`) for details on the convolution operator. See
* **Getting more help** below.
*
* Finally:
*
* ```php
* $im->writeToFile($argv[2]);
* ```
*
* `Image::writeToFile` writes an image back to the filesystem. It can
* write any format supported by vips: the file type is set from the filename
* suffix. You can write formatted images to strings, and pixel values to
* arrays.
*
* # Getting more help
*
* This binding lets you call the complete C API almost directly. You should
* [consult the C docs](https://jcupitt.github.io/libvips/API/current)
* for full details on the operations that are available and
* the arguments they take. There's a handy [function
* list](https://jcupitt.github.io/libvips/API/current/func-list.html)
* which summarises the operations in the library. You can use the `vips`
* command-line interface to get help as well, for example:
*
* ```
* $ vips embed
* embed an image in a larger image
* usage:
* embed in out x y width height
* where:
* in - Input image, input VipsImage
* out - Output image, output VipsImage
* x - Left edge of input in output, input gint
* default: 0
* min: -1000000000, max: 1000000000
* y - Top edge of input in output, input gint
* default: 0
* min: -1000000000, max: 1000000000
* width - Image width in pixels, input gint
* default: 1
* min: 1, max: 1000000000
* height - Image height in pixels, input gint
* default: 1
* min: 1, max: 1000000000
* optional arguments:
* extend - How to generate the extra pixels, input VipsExtend
* default: black
* allowed: black, copy, repeat, mirror, white, background
* background - Colour for background pixels, input VipsArrayDouble
* operation flags: sequential-unbuffered
* ```
*
* You can call this from PHP as:
*
* ```php
* $out = $in->embed($x, $y, $width, $height,
* ['extend' => 'copy', 'background' => [1, 2, 3]]);
* ```
*
* `'background'` can also be a simple constant, such as `12`, see below.
*
* The `vipsheader` command-line program is an easy way to see all the
* properties of an image. For example:
*
* ```
* $ vipsheader -a ~/pics/k2.jpg
* /home/john/pics/k2.jpg: 1450x2048 uchar, 3 bands, srgb, jpegload
* width: 1450
* height: 2048
* bands: 3
* format: 0 - uchar
* coding: 0 - none
* interpretation: 22 - srgb
* xoffset: 0
* yoffset: 0
* xres: 2.834646
* yres: 2.834646
* filename: "/home/john/pics/k2.jpg"
* vips-loader: jpegload
* jpeg-multiscan: 0
* ipct-data: VIPS_TYPE_BLOB, data = 0x20f0010, length = 332
* ```
*
* You can access any of these fields as PHP properties of the `Image` class.
* Use `$image->get('ipct-data')` for property names which are not valid under
* PHP syntax.
*
* # Automatic wrapping
*
* This binding has a `__call()` method and uses
* it to look up vips operations. For example, the libvips operation `embed`,
* which appears in C as `vips_embed()`, appears in PHP as `Image::embed`.
*
* The operation's list of required arguments is searched and the first input
* image is set to the value of `self`. Operations which do not take an input
* image, such as `Image::black`, appear as static methods. The remainder of
* the arguments you supply in the function call are used to set the other
* required input arguments. If the final supplied argument is an array, it is
* used to set any optional input arguments. The result is the required output
* argument if there is only one result, or an array of values if the operation
* produces several results.
*
* For example, `Image::min`, the vips operation that searches an image for
* the minimum value, has a large number of optional arguments. You can use it
* to find the minimum value like this:
*
* ```php
* $min_value = $image->min();
* ```
*
* You can ask it to return the position of the minimum with `x` and `y`.
*
* ```php
* $result = $image->min(['x' => true, 'y' => true]);
* $min_value = $result['out'];
* $x_pos = $result['x'];
* $y_pos = $result['y'];
* ```
*
* Now `x_pos` and `y_pos` will have the coordinates of the minimum value.
* There's actually a convenience function for this, `Image::minpos`, see
* below.
*
* You can also ask for the top *n* minimum, for example:
*
* ```php
* $result = $image->min(['size' => 10, 'x_array' => true, 'y_array' => true]);
* $x_pos = $result['x_array'];
* $y_pos = $result['y_array'];
* ```
*
* Now `x_pos` and `y_pos` will be 10-element arrays.
*
* Because operations are member functions and return the result image, you can
* chain them. For example, you can write:
*
* ```php
* $result_image = $image->real()->cos();
* ```
*
* to calculate the cosine of the real part of a complex image.
*
* libvips types are also automatically wrapped and unwrapped. The binding
* looks at the type
* of argument required by the operation and converts the value you supply,
* when it can. For example, `Image::linear` takes a `VipsArrayDouble` as
* an argument
* for the set of constants to use for multiplication. You can supply this
* value as an integer, a float, or some kind of compound object and it
* will be converted for you. You can write:
*
* ```php
* $result = $image->linear(1, 3);
* $result = $image->linear(12.4, 13.9);
* $result = $image->linear([1, 2, 3], [4, 5, 6]);
* $result = $image->linear(1, [4, 5, 6]);
* ```
*
* And so on. You can also use `Image::add()` and friends, see below.
*
* It does a couple of more ambitious conversions. It will automatically convert
* to and from the various vips types, like `VipsBlob` and `VipsArrayImage`. For
* example, you can read the ICC profile out of an image like this:
*
* ```php
* $profile = $image->get('icc-profile-data');
* ```
*
* and `$profile` will be a PHP string.
*
* If an operation takes several input images, you can use a constant for all but
* one of them and the wrapper will expand the constant to an image for you. For
* example, `Image::ifthenelse()` uses a condition image to pick pixels
* between a then and an else image:
*
* ```php
* $result = $condition->ifthenelse($then_image, $else_image);
* ```
*
* You can use a constant instead of either the then or the else parts and it
* will be expanded to an image for you. If you use a constant for both then and
* else, it will be expanded to match the condition image. For example:
*
* ```php
* $result = $condition->ifthenelse([0, 255, 0], [255, 0, 0]);
* ```
*
* Will make an image where true pixels are green and false pixels are red.
*
* This is useful for `Image::bandjoin`, the thing to join two or more
* images up bandwise. You can write:
*
* ```php
* $rgba = $rgb->bandjoin(255);
* ```
*
* to append a constant 255 band to an image, perhaps to add an alpha channel. Of
* course you can also write:
*
* ```php
* $result = $image->bandjoin($image2);
* $result = $image->bandjoin([image2, image3]);
* $result = Image::bandjoin([image1, image2, image3]);
* $result = $image->bandjoin([image2, 255]);
* ```
*
* and so on.
*
* # Array access
*
* Images can be treated as arrays of bands. You can write:
*
* ```php
* $result = $image[1];
* ```
*
* to get band 1 from an image (green, in an RGB image).
*
* You can assign to bands as well. You can write:
*
* ```php
* $image[1] = $other_image;
* ```
*
* And band 1 will be replaced by all the bands in `$other_image` using
* `bandjoin`. Use no offset to mean append, use -1 to mean prepend:
*
* ```php
* $image[] = $other_image; // append bands from other
* $image[-1] = $other_image; // prepend bands from other
* ```
*
* You can use number and array constants as well, for example:
*
* ```php
* $image[] = 255; // append a constant 255
* $image[1] = [1, 2, 3]; // swap band 1 for three constant bands
* ```
*
* Finally, you can delete bands with `unset`:
*
* ```php
* unset($image[1]); // remove band 1
* ```
*
* # Exceptions
*
* The wrapper spots errors from vips operations and throws
* `Vips\Exception`. You can catch it in the usual way.
*
* # Draw operations
*
* Paint operations like `Image::draw_circle` and `Image::draw_line`
* modify their input image. This
* makes them hard to use with the rest of libvips: you need to be very careful
* about the order in which operations execute or you can get nasty crashes.
*
* The wrapper spots operations of this type and makes a private copy of the
* image in memory before calling the operation. This stops crashes, but it does
* make it inefficient. If you draw 100 lines on an image, for example, you'll
* copy the image 100 times. The wrapper does make sure that memory is recycled
* where possible, so you won't have 100 copies in memory.
*
* If you want to avoid the copies, you'll need to call drawing operations
* yourself.
*
* # Thumbnailing
*
* The thumbnailing functionality is implemented by `Vips\Image::thumbnail` and
* `Vips\Image::thumbnail_buffer` (which thumbnails an image held as a string).
*
* You could write:
*
* ```php
* $filename = 'image.jpg';
* $image = Vips\Image::thumbnail($filename, 200, ['height' => 200]);
* $image->writeToFile('my-thumbnail.jpg');
* ```
*
* # Resample
*
* There are three types of operation in this section.
*
* First, `->affine()` applies an affine transform to an image.
* This is any sort of 2D transform which preserves straight lines;
* so any combination of stretch, sheer, rotate and translate.
* You supply an interpolator for it to use to generate pixels
* (@see Image::newInterpolator()). It will not produce good results for
* very large shrinks: you'll see aliasing.
*
* `->reduce()` is like `->affine()`, but it can only shrink images,
* it can't enlarge, rotate, or skew.
* It's very fast and uses an adaptive kernel (@see Kernel for possible values)
* for interpolation. It will be slow for very large shrink factors.
*
* `->shrink()` is a fast block shrinker. It can quickly reduce images by large
* integer factors. It will give poor results for small size reductions:
* again, you'll see aliasing.
*
* Next, `->resize()` specialises in the common task of image reduce and enlarge.
* It strings together combinations of `->shrink()`, `->reduce()`, `->affine()`
* and others to implement a general, high-quality image resizer.
*
* Finally, `->mapim()` can apply arbitrary 2D image transforms to an image.
*
* # Expansions
*
* Some vips operators take an enum to select an action, for example
* `Image::math` can be used to calculate sine of every pixel like this:
*
* ```php
* $result = $image->math('sin');
* ```
*
* This is annoying, so the wrapper expands all these enums into separate members
* named after the enum. So you can write:
*
* ```php
* $result = $image->sin();
* ```
*
* # Convenience functions
*
* The wrapper defines a few extra useful utility functions:
* `Image::get`, `Image::set`, `Image::bandsplit`,
* `Image::maxpos`, `Image::minpos`,
* `Image::median`. See below.
*
* # Logging
*
* Use `Config::setLogger` to enable logging in the usual manner. A
* sample logger, handy for debugging, is defined in `Vips\DebugLogger`. You
* can enable debug logging with:
*
* ```php
* Vips\Config::setLogger(new Vips\DebugLogger);
* ```
*
* # Configuration
*
* You can use the methods in `Vips\Config` to set various global properties of
* the library. For example, you can control the size of the libvips cache,
* or the size of the worker threadpools that libvips uses to evaluate images.
*
* @category Images
* @package Jcupitt\Vips
* @author John Cupitt <[email protected]>
* @copyright 2016 John Cupitt
* @license https://opensource.org/licenses/MIT MIT
* @link https://github.com/jcupitt/php-vips
*/
class Image extends ImageAutodoc implements \ArrayAccess
{
/**
* A pointer to the underlying VipsImage. This is the same as the
* GObject, just cast to VipsImage to help FFI.
*
* @internal
*/
public \FFI\CData $pointer;
/**
* Wrap an Image around an underlying CData pointer.
*
* Don't call this yourself, users should stick to (for example)
* Image::newFromFile().
*
* @internal
*/
public function __construct(\FFI\CData $pointer)
{
$this->pointer = \FFI::cast(FFI::ctypes("VipsImage"), $pointer);
parent::__construct($pointer);
}
/**
* Apply a func to every numeric member of $value. Useful for self::subtract
* etc.
*
* @param mixed $value The thing we walk.
* @param \Closure $func Apply this.
*
* @return mixed The updated $value.
*
* @internal
*/
private static function mapNumeric($value, \Closure $func)
{
if (is_numeric($value)) {
$value = $func($value);
} elseif (is_array($value)) {
array_walk_recursive($value, function (&$value) use ($func) {
$value = self::mapNumeric($value, $func);
});
}
return $value;
}
/**
* Is a $value a rectangular 2D array?
*
* @param mixed $value Test this.
*
* @return bool true if this is a 2D array.
*
* @internal
*/
private static function is2D($value): bool
{
if (!is_array($value)) {
return false;
}
if (!is_array($value[0])) {
return false;
}
$width = count($value[0]);
foreach ($value as $row) {
if (!is_array($row) || count($row) !== $width) {
return false;
}
}
return true;
}
/**
* Is $value something that we should treat as an image?
*
* Instance of Image, or 2D arrays are images; 1D arrays or single values
* are constants.
*
* @param mixed $value The value to test.
*
* @return bool true if this is like an image.
*
* @internal
*/
public static function isImageish($value): bool
{
return self::is2D($value) || $value instanceof Image;
}
/**
* Turn a constant (eg. 1, '12', [1, 2, 3], [[1]]) into an image using
* this as a guide.
*
* @param mixed $value Turn this into an image.
*
* @throws Exception
*
* @return Image The image we created.
*
* @internal
*/
public function imageize($value): Image
{
if ($value instanceof Image) {
return $value;
} elseif (self::is2D($value)) {
return self::newFromArray($value);
} else {
return $this->newFromImage($value);
}
}
/**
* Run a function expecting a complex image. If the image is not in complex
* format, try to make it complex by joining adjacant bands as real and
* imaginary.
*
* @param \Closure $func The function to run.
* @param Image $image The image to run the function on.
*
* @throws Exception
*
* @return Image A new Image.
*
* @internal
*/
private static function runCmplx(\Closure $func, Image $image): Image
{
$original_format = $image->format;
if ($image->format != 'complex' && $image->format != 'dpcomplex') {
if ($image->bands % 2 != 0) {
throw new Exception('not an even number of bands');
}
if ($image->format != 'float' && $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 = $func($image);
if ($original_format != 'complex' && $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;
}
/**
* Handy for things like self::more. Call a 2-ary vips operator like
* 'more', but if the arg is not an image (i.e. it's a constant), call
* 'more_const' instead.
*
* @param mixed $other The right-hand argument.
* @param string $base The base part of the operation name.
* @param string $op The action to invoke.
* @param array $options An array of options to pass to the operation.
*
* @throws Exception
*
* @return mixed The operation result.
*
* @internal
*/
private function callEnum(
$other,
string $base,
string $op,
array $options = []
) {
if (self::isImageish($other)) {
return VipsOperation::call($base, $this, [$other, $op], $options);
} else {
return VipsOperation::call(
$base . '_const',
$this,
[$op, $other],
$options
);
}
}
/**
* Find the name of the load operation vips will use to load a file, for
* example "VipsForeignLoadJpegFile". You can use this to work out what
* options to pass to newFromFile().
*
* @param string $filename The file to test.
*
* @return string|null The name of the load operation, or null.
*/
public static function findLoad(string $filename): ?string
{
return FFI::vips()->vips_foreign_find_load($filename);
}
/**
* Create a new Image from a file on disc.
*
* See the [main libvips
* documentation](https://www.libvips.org/API/current/VipsImage.html#vips-image-new-from-file)
* for a more detailed explaination.
*
* @param string $name The file to open.
* @param array $options Any options to pass on to the load operation.
*
* @throws Exception
*
* @return Image A new Image.
*/
public static function newFromFile(
string $name,
array $options = []
): Image {
$filename = Utils::filenameGetFilename($name);
$string_options = Utils::filenameGetOptions($name);
$loader = self::findLoad($filename);
if ($loader == null) {
throw new Exception();
}
if (strlen($string_options) != 0) {
$options = array_merge([
"string_options" => $string_options,
], $options);
}
return VipsOperation::call($loader, null, [$filename], $options);
}
/**
* Find the name of the load operation vips will use to load a buffer, for
* example 'VipsForeignLoadJpegBuffer'. You can use this to work out what
* options to pass to newFromBuffer().
*
* @param string $buffer The formatted image to test.
*
* @return string|null The name of the load operation, or null.
*/
public static function findLoadBuffer(string $buffer): ?string
{
return FFI::vips()->
vips_foreign_find_load_buffer($buffer, strlen($buffer));
}
/**
* Create a new Image from a compressed image held as a string.
*
* @param string $buffer The formatted image to open.
* @param string $string_options Any text-style options to pass to the
* selected loader.
* @param array $options Options to pass on to the load operation.
*
* @throws Exception
*
* @return Image A new Image.
*/
public static function newFromBuffer(
string $buffer,
string $string_options = '',
array $options = []
): Image {
$loader = self::findLoadBuffer($buffer);
if ($loader == null) {
throw new Exception();
}
if (strlen($string_options) != 0) {
$options = array_merge([
"string_options" => $string_options,
], $options);
}
return VipsOperation::call($loader, null, [$buffer], $options);
}
/**
* Create a new Image from a php array.
*
* 2D arrays become 2D images. 1D arrays become 2D images with height 1.
*
* @param array $array The array to make the image from.
* @param float $scale The "scale" metadata item. Useful for integer
* convolution masks.
* @param float $offset The "offset" metadata item. Useful for integer
* convolution masks.
*
* @throws Exception
*
* @return Image A new Image.
*/
public static function newFromArray(
array $array,
float $scale = 1.0,
float $offset = 0.0
): Image {
if (!self::is2D($array)) {
$array = [$array];
}
$height = count($array);
$width = count($array[0]);
$n = $width * $height;
$a = \FFI::new("double[$n]", true, true);
for ($y = 0; $y < $height; $y++) {
for ($x = 0; $x < $width; $x++) {
$a[$x + $y * $width] = $array[$y][$x];
}
}
$pointer = FFI::vips()->
vips_image_new_matrix_from_array($width, $height, $a, $n);
if ($pointer == null) {
throw new Exception();
}
$result = new Image($pointer);
$result->setType(FFI::gtypes("gdouble"), 'scale', $scale);
$result->setType(FFI::gtypes("gdouble"), 'offset', $offset);
return $result;
}
/**
* Wraps an Image around an area of memory containing a C-style array.
*
* @param mixed $data C-style array.
* @param int $width Image width in pixels.
* @param int $height Image height in pixels.
* @param int $bands Number of bands.
* @param string $format Band format. (@see BandFormat)
*
* @throws Exception
*
* @return Image A new Image.
*/
public static function newFromMemory(
$data,
int $width,
int $height,
int $bands,
string $format
): Image {
/* Take a copy of the memory area to avoid lifetime issues.
*
* TODO add a references system instead, see pyvips.
*/
$pointer = FFI::vips()->vips_image_new_from_memory_copy(
$data,
strlen($data),
$width,
$height,
$bands,
$format
);
if ($pointer == null) {
throw new Exception();
}
return new Image($pointer);
}
/**
* Deprecated thing to make an interpolator.
*
* See Interpolator::newFromName() for the new thing.
*/
public static function newInterpolator(string $name): Interpolate
{
return Interpolate::newFromName($name);
}
/**
* Create a new image from a constant.
*
* The new image has the same width, height, format, interpretation, xres,
* yres, xoffset, yoffset as $this, but each pixel has the constant value
* $value.
*
* Pass a single number to make a one-band image, pass an array of numbers
* to make an N-band image.
*
* @param mixed $value The value to set each pixel to.
*
* @throws Exception
*
* @return Image A new Image.
*/
public function newFromImage($value): Image
{
$pixel = static::black(1, 1)->add($value)->cast($this->format);
$image = $pixel->embed(
0,
0,
$this->width,
$this->height,
['extend' => Extend::COPY]
);
return $image->copy([
'interpretation' => $this->interpretation,
'xres' => $this->xres,
'yres' => $this->yres,
'xoffset' => $this->xoffset,
'yoffset' => $this->yoffset
]);
}
/**
* Find the name of the load operation vips will use to load a VipsSource, for
* example 'VipsForeignLoadJpegSource'. You can use this to work out what
* options to pass to newFromSource().
*
* @param Source $source The source to test
* @return string|null The name of the load operation, or null.
*/
public static function findLoadSource(Source $source): ?string
{
return FFI::vips()->vips_foreign_find_load_source(\FFI::cast(FFI::ctypes('VipsSource'), $source->pointer));
}
/**
* @throws Exception
*/
public static function newFromSource(Source $source, string $string_options = '', array $options = []): self
{
$loader = self::findLoadSource($source);
if ($loader === null) {
throw new Exception('unable to load from source');
}
if ($string_options !== '') {
$options = array_merge([
"string_options" => $string_options,
], $options);
}
return VipsOperation::call($loader, null, [$source], $options);
}
/**
* Write an image to a file.
*
* @param string $name The file to write the image to.
* @param array $options Any options to pass on to the selected save
* operation.
*
* @throws Exception
*
* @return void
*/
public function writeToFile(string $name, array $options = []): void
{
$filename = Utils::filenameGetFilename($name);
$string_options = Utils::filenameGetOptions($name);
$saver = FFI::vips()->vips_foreign_find_save($filename);
if ($saver == "") {
throw new Exception();
}
if (strlen($string_options) != 0) {
$options = array_merge([
"string_options" => $string_options,
], $options);
}
$result = VipsOperation::call($saver, $this, [$filename], $options);
if ($result === -1) {
throw new Exception();
}
}
/**
* Write an image to a formatted string.
*
* @param string $suffix The file type suffix, eg. ".jpg".
* @param array $options Any options to pass on to the selected save
* operation.
*
* @throws Exception
*
* @return string The formatted image.
*/
public function writeToBuffer(string $suffix, array $options = []): string
{
$filename = Utils::filenameGetFilename($suffix);
$string_options = Utils::filenameGetOptions($suffix);
$saver = FFI::vips()->vips_foreign_find_save_buffer($filename);
if ($saver == "") {
throw new Exception();
}