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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
use crate::ffi;
use crate::{Error, Result, VipsInterpolate, take_vips_error};
use std::ffi::CString;
use std::marker::PhantomData;
use std::os::raw::{c_char, c_int, c_void};
use std::path::Path;
use std::ptr::{null, null_mut};
use vips_sys::{
VipsBandFormat, VipsCombineMode, VipsCompassDirection, VipsDirection, VipsExtend,
VipsInteresting, VipsKernel, VipsSize,
};
#[cfg(feature = "v8_18")]
mod v8_18;
/// Number of colour bands used by an interpretation (libvips 8.18+).
#[cfg(feature = "v8_18")]
pub fn interpretation_bands(interpretation: vips_sys::VipsInterpretation) -> i32 {
// SAFETY: the C function accepts a value enum and returns a scalar.
unsafe { vips_sys::vips_interpretation_bands(interpretation) }
}
/// Convert a filesystem path to a C string without intermediate UTF-8 `Vec` allocations.
fn path_to_cstring(path: &Path) -> Result<CString> {
#[cfg(unix)]
{
use std::os::unix::ffi::OsStrExt;
CString::new(path.as_os_str().as_bytes())
.map_err(|e| Error::InitFailed(format!("invalid path: {e}")))
}
#[cfg(not(unix))]
{
CString::new(path.to_string_lossy().as_bytes())
.map_err(|e| Error::InitFailed(format!("invalid path: {e}")))
}
}
fn validate_memory(
buf: &[u8],
width: u32,
height: u32,
bands: u8,
format: VipsBandFormat,
) -> Result<()> {
use VipsBandFormat::*;
let (sample_bytes, alignment) = match format {
VIPS_FORMAT_UCHAR | VIPS_FORMAT_CHAR => (1, 1),
VIPS_FORMAT_USHORT | VIPS_FORMAT_SHORT => (2, 2),
VIPS_FORMAT_UINT | VIPS_FORMAT_INT | VIPS_FORMAT_FLOAT => (4, 4),
VIPS_FORMAT_COMPLEX => (8, 4),
VIPS_FORMAT_DOUBLE => (8, 8),
VIPS_FORMAT_DPCOMPLEX => (16, 8),
_ => return Err(Error::Other("invalid memory image band format".into())),
};
let required = (width as usize)
.checked_mul(height as usize)
.and_then(|n| n.checked_mul(bands as usize))
.and_then(|n| n.checked_mul(sample_bytes));
if width == 0
|| height == 0
|| bands == 0
|| width > i32::MAX as u32
|| height > i32::MAX as u32
|| required.is_none_or(|n| n > buf.len())
|| buf.as_ptr().align_offset(alignment) != 0
{
return Err(Error::Other(
"memory image requires positive i32 dimensions, enough bytes, and aligned samples"
.into(),
));
}
Ok(())
}
/// Safe RAII wrapper around a libvips `VipsImage*`.
///
/// The raw pointer is private. Use the safe methods, or [`VipsImage::as_ptr`]
/// when you must pass the handle into a lower-level FFI call.
///
/// # Lifetimes
/// `'a` ties images created from borrowed buffers to that buffer's lifetime.
/// Owned constructors (`from_file`, `from_memory`) use an unbound lifetime.
///
/// # Thread safety
/// Not `Send`/`Sync`. Do not share an image across threads without external
/// synchronization. libvips pipelines are otherwise process-global.
///
/// # Example
/// ```no_run
/// use vips::*;
///
/// fn main() -> Result<()> {
/// let _instance = VipsInstance::new("app_test", true)?;
/// let thumb = VipsImage::thumbnail_file("input.jpg", 100, 100, VipsSize::VIPS_SIZE_BOTH)?;
/// thumb.write_to_file("thumb.jpg")?;
/// Ok(())
/// }
/// ```
pub struct VipsImage<'a> {
/// Unique ownership of a `VipsImage*`; always non-null.
c: std::ptr::NonNull<vips_sys::VipsImage>,
marker: PhantomData<&'a ()>,
/// Only explicitly owned memory can be modified without detaching first.
writable: bool,
}
impl<'a> Drop for VipsImage<'a> {
fn drop(&mut self) {
// SAFETY: exclusive refcount ownership; NonNull is never null.
unsafe { ffi::unref(self.c.as_ptr().cast()) };
}
}
/// Free the boxed pixel buffer after libvips closes a memory image.
///
/// # Safety
/// Called by GObject with `user_data` from `g_signal_connect_data`; must be a
/// `Box<Vec<u8>>` allocated by `from_memory`.
unsafe extern "C" fn image_postclose(_ptr: *mut vips_sys::VipsImage, user_data: *mut c_void) {
if user_data.is_null() {
return;
}
// SAFETY: reconstructed exactly as boxed in `from_memory`.
let b: Box<Vec<u8>> = unsafe { Box::from_raw(user_data as *mut Vec<u8>) };
drop(b);
}
impl<'a> VipsImage<'a> {
/// Borrow the underlying libvips pointer for FFI.
///
/// The pointer is valid while `self` is alive. Do not unref it.
#[inline]
pub fn as_ptr(&self) -> *mut vips_sys::VipsImage {
self.c.as_ptr()
}
/// Take ownership of a non-null `VipsImage*`.
///
/// # Safety
/// `ptr` must be a uniquely owned, non-null `VipsImage*` whose refcount is
/// transferred to the returned value (`Drop` will unref it).
pub(crate) unsafe fn from_raw(ptr: *mut vips_sys::VipsImage) -> VipsImage<'a> {
let c = std::ptr::NonNull::new(ptr).expect("VipsImage::from_raw(null)");
VipsImage {
c,
marker: PhantomData,
writable: false,
}
}
/// Detach borrowed or shared pixels before an in-place draw. Unlike
/// vips_image_copy_memory, writing to a fresh memory image always copies
/// even when the input is already backed by a caller's immutable slice.
fn ensure_writable(&mut self) -> Result<()> {
if !self.writable {
let mut copy = Self::new_memory()?;
// SAFETY: both images are live; the destination owns its storage.
let ret = unsafe { vips_sys::vips_image_write(self.as_ptr(), copy.as_ptr()) };
ffi::ret_to_result(ret)?;
copy.writable = true;
*self = copy;
}
Ok(())
}
//
// ─── CONSTRUCTORS ───────────────────────────────────────────────────────────────
//
/// Create a new empty VipsImage.
///
/// # Errors
/// Returns an error if the image creation fails.
///
/// # Example
/// ```no_run
/// use vips::*;
///
/// fn main() -> Result<()> {
/// let _instance = VipsInstance::new("app_test", true)?;
/// let img = VipsImage::new()?;
/// Ok(())
/// }
/// ```
pub fn new() -> Result<VipsImage<'a>> {
// SAFETY: libvips allocates a fresh empty image or returns null.
let c = unsafe { vips_sys::vips_image_new() };
result(c)
}
/// Create a new empty VipsImage in memory.
///
/// # Errors
/// Returns an error if the image creation fails.
///
/// # Example
/// ```no_run
/// use vips::*;
///
/// fn main() -> Result<()> {
/// let _instance = VipsInstance::new("app_test", true)?;
/// let img = VipsImage::new_memory()?;
/// Ok(())
/// }
/// ```
pub fn new_memory() -> Result<VipsImage<'a>> {
// SAFETY: libvips allocates a fresh memory-backed image or returns null.
let c = unsafe { vips_sys::vips_image_new_memory() };
result(c)
}
/// Create a VipsImage from a file.
///
/// # Arguments
/// * `path` - The file path to load the image from.
///
/// # Errors
/// Returns an error if the image loading fails.
///
/// # Returns
/// A `Result` containing the loaded `VipsImage` or an error.
///
/// # Example
/// ```no_run
/// use vips::*;
///
/// fn main() -> Result<()> {
/// let _instance = VipsInstance::new("app_test", true)?;
/// let img = VipsImage::from_file("input.jpg")?;
/// Ok(())
/// }
/// ```
pub fn from_file(path: impl AsRef<Path>) -> Result<VipsImage<'a>> {
let path = path_to_cstring(path.as_ref())?;
unsafe {
let ptr = vips_sys::vips_image_new_from_file(path.as_ptr(), null() as *const c_char);
result(ptr)
}
}
/// Load a file with an explicit access hint. Use `VIPS_ACCESS_SEQUENTIAL`
/// for one-pass pipelines; random access is needed for arbitrary regions.
pub fn from_file_with_access(
path: impl AsRef<Path>,
access: vips_sys::VipsAccess,
) -> Result<VipsImage<'a>> {
let path = path_to_cstring(path.as_ref())?;
// SAFETY: path is NUL-terminated and access is passed as a C enum.
let ptr = unsafe {
vips_sys::vips_image_new_from_file(
path.as_ptr(),
c"access".as_ptr(),
access,
null() as *const c_char,
)
};
result(ptr)
}
/// Create a VipsImage from a memory buffer.
///
/// # Arguments
/// * `buf` - The buffer containing the image data.
/// * `width` - The width of the image.
/// * `height` - The height of the image.
/// * `bands` - The number of bands (channels) in the image.
/// * `format` - The band format of the image.
///
/// # Errors
/// Returns an error if the image creation fails.
///
/// # Example
/// ```no_run
/// use vips::*;
///
/// fn main() -> Result<()> {
/// let _instance = VipsInstance::new("app_test", true)?;
/// let img_data: Vec<u8> = vec![/* image data */];
/// let img = VipsImage::from_memory(img_data, 800, 600, 3, VipsBandFormat::VIPS_FORMAT_UCHAR)?;
/// Ok(())
/// }
/// ```
///
pub fn from_memory(
buf: Vec<u8>,
width: u32,
height: u32,
bands: u8,
format: VipsBandFormat,
) -> Result<VipsImage<'a>> {
validate_memory(&buf, width, height, bands, format)?;
let b = buf;
let c = unsafe {
vips_sys::vips_image_new_from_memory(
b.as_ptr() as *const c_void,
b.len(),
width as i32,
height as i32,
bands as i32,
format,
)
};
if c.is_null() {
return Err(Error::Vips(
take_vips_error().unwrap_or_else(|| "Unknown error from libvips".to_string()),
));
}
let bb: Box<Vec<u8>> = Box::new(b);
let raw: *mut c_void = Box::into_raw(bb) as *mut c_void;
// SAFETY: `c` is a valid image; callback frees `raw` exactly once on close.
unsafe {
let callback: unsafe extern "C" fn() =
std::mem::transmute(image_postclose as *const ());
vips_sys::g_signal_connect_data(
c as *mut c_void,
c"postclose".as_ptr(),
Some(callback),
raw,
None,
vips_sys::GConnectFlags::G_CONNECT_AFTER,
);
};
// SAFETY: unique ownership transferred to the wrapper.
let mut image = unsafe { VipsImage::from_raw(c) };
image.writable = true;
Ok(image)
}
/// Create a VipsImage from a memory buffer reference.
///
/// # Arguments
/// * `buf` - The buffer slice containing the image data.
/// * `width` - The width of the image.
/// * `height` - The height of the image.
/// * `bands` - The number of bands (channels) in the image.
/// * `format` - The band format of the image.
///
/// # Returns
/// A `Result` containing the created `VipsImage` or an error.
///
/// # Errors
/// Returns an error if the image creation fails.
///
/// # Example
/// ```no_run
/// use vips::*;
///
/// fn main() -> Result<()> {
/// let _instance = VipsInstance::new("app_test", true)?;
/// let img_data: &[u8] = &[/* image data */];
/// let img = VipsImage::from_memory_reference(img_data, 800, 600, 3, VipsBandFormat::VIPS_FORMAT_UCHAR)?;
/// Ok(())
/// }
/// ```
///
pub fn from_memory_reference(
buf: &'a [u8],
width: u32,
height: u32,
bands: u8,
format: VipsBandFormat,
) -> Result<VipsImage<'a>> {
validate_memory(buf, width, height, bands, format)?;
let c = unsafe {
vips_sys::vips_image_new_from_memory(
buf.as_ptr() as *const c_void,
buf.len(),
width as i32,
height as i32,
bands as i32,
format,
)
};
result(c)
}
/// Create a VipsImage from a byte buffer.
///
/// # Arguments
/// * `buf` - The buffer slice containing the image data.
///
/// # Returns
/// A `Result` containing the created `VipsImage` or an error.
///
/// # Errors
/// Returns an error if the image creation fails.
///
/// # Example
/// ```no_run
/// use vips::*;
///
/// fn main() -> Result<()> {
/// let _instance = VipsInstance::new("app_test", true)?;
/// let img_data: &[u8] = &[/* image data */];
/// let img = VipsImage::from_buffer(img_data)?;
/// Ok(())
/// }
/// ```
pub fn from_buffer(buf: &'a [u8]) -> Result<VipsImage<'a>> {
let c = unsafe {
vips_sys::vips_image_new_from_buffer(
buf.as_ptr() as *const c_void,
buf.len(),
null(),
null() as *const c_char,
)
};
result(c)
}
/// Decode encoded bytes with an explicit access hint. The input bytes
/// must outlive the returned image and every derived lazy pipeline.
pub fn from_buffer_with_access(
buf: &'a [u8],
access: vips_sys::VipsAccess,
) -> Result<VipsImage<'a>> {
// SAFETY: input remains borrowed by the returned image; varargs end in NULL.
let ptr = unsafe {
vips_sys::vips_image_new_from_buffer(
buf.as_ptr().cast(),
buf.len(),
c"".as_ptr(),
c"access".as_ptr(),
access,
null() as *const c_char,
)
};
result(ptr)
}
//
// ─── DRAW ───────────────────────────────────────────────────────────────────────
//
/// Draw a rectangle on the image.
///
/// # Arguments
/// * `ink` - The color to use for drawing, as a slice of f64 values.
/// * `left` - The left coordinate of the rectangle.
/// * `top` - The top coordinate of the rectangle.
/// * `width` - The width of the rectangle.
/// * `height` - The height of the rectangle.
///
/// # Returns
/// A `Result` indicating success or failure.
///
/// # Errors
/// Returns an error if the drawing operation fails.
///
/// # Example
/// ```no_run
/// use vips::*;
///
/// fn main() -> Result<()> {
/// let _instance = VipsInstance::new("app_test", true)?;
/// let mut img = VipsImage::from_file("input.jpg")?;
/// img.draw_rect(&[255.0, 0.0, 0.0], 10, 10, 100, 50)?;
/// img.write_to_file("output.jpg")?;
/// Ok(())
/// }
/// ```
pub fn draw_rect(
&mut self,
ink: &[f64],
left: u32,
top: u32,
width: u32,
height: u32,
) -> Result<()> {
self.ensure_writable()?;
let ret = unsafe {
vips_sys::vips_draw_rect(
self.c.as_ptr(),
ink.as_ptr() as *mut f64,
ink.len() as i32,
left as i32,
top as i32,
width as i32,
height as i32,
null() as *const c_char,
)
};
result_draw(ret)
}
pub fn draw_rect1(
&mut self,
ink: f64,
left: u32,
top: u32,
width: u32,
height: u32,
) -> Result<()> {
self.ensure_writable()?;
let ret = unsafe {
vips_sys::vips_draw_rect1(
self.c.as_ptr(),
ink,
left as i32,
top as i32,
width as i32,
height as i32,
null() as *const c_char,
)
};
result_draw(ret)
}
pub fn draw_point(&mut self, ink: &[f64], x: i32, y: i32) -> Result<()> {
self.ensure_writable()?;
let ret = unsafe {
vips_sys::vips_draw_point(
self.c.as_ptr(),
ink.as_ptr() as *mut f64,
ink.len() as i32,
x,
y,
null() as *const c_char,
)
};
result_draw(ret)
}
pub fn draw_point1(&mut self, ink: f64, x: i32, y: i32) -> Result<()> {
self.ensure_writable()?;
let ret = unsafe {
vips_sys::vips_draw_point1(self.c.as_ptr(), ink, x, y, null() as *const c_char)
};
result_draw(ret)
}
pub fn draw_image(
&mut self,
img: &VipsImage,
x: i32,
y: i32,
mode: VipsCombineMode,
) -> Result<()> {
self.ensure_writable()?;
let ret = unsafe {
vips_sys::vips_draw_image(
self.c.as_ptr(),
img.as_ptr(),
x,
y,
c"mode".as_ptr(),
mode,
null() as *const c_char,
)
};
result_draw(ret)
}
pub fn draw_mask(&mut self, ink: &[f64], mask: &VipsImage, x: i32, y: i32) -> Result<()> {
self.ensure_writable()?;
let ret = unsafe {
vips_sys::vips_draw_mask(
self.c.as_ptr(),
ink.as_ptr() as *mut f64,
ink.len() as i32,
mask.as_ptr(),
x,
y,
null() as *const c_char,
)
};
result_draw(ret)
}
pub fn draw_mask1(&mut self, ink: f64, mask: &VipsImage, x: i32, y: i32) -> Result<()> {
self.ensure_writable()?;
let ret = unsafe {
vips_sys::vips_draw_mask1(
self.c.as_ptr(),
ink,
mask.as_ptr(),
x,
y,
null() as *const c_char,
)
};
result_draw(ret)
}
pub fn draw_line(&mut self, ink: &[f64], x1: i32, y1: i32, x2: i32, y2: i32) -> Result<()> {
self.ensure_writable()?;
let ret = unsafe {
vips_sys::vips_draw_line(
self.c.as_ptr(),
ink.as_ptr() as *mut f64,
ink.len() as i32,
x1,
y1,
x2,
y2,
null() as *const c_char,
)
};
result_draw(ret)
}
pub fn draw_line1(&mut self, ink: f64, x1: i32, y1: i32, x2: i32, y2: i32) -> Result<()> {
self.ensure_writable()?;
let ret = unsafe {
vips_sys::vips_draw_line1(
self.c.as_ptr(),
ink,
x1,
y1,
x2,
y2,
null() as *const c_char,
)
};
result_draw(ret)
}
pub fn draw_circle(&mut self, ink: &[f64], cx: i32, cy: i32, r: i32, fill: bool) -> Result<()> {
self.ensure_writable()?;
let ret = unsafe {
vips_sys::vips_draw_circle(
self.c.as_ptr(),
ink.as_ptr() as *mut f64,
ink.len() as i32,
cx,
cy,
r,
c"fill".as_ptr(),
fill as i32,
null() as *const c_char,
)
};
result_draw(ret)
}
pub fn draw_circle1(&mut self, ink: f64, cx: i32, cy: i32, r: i32, fill: bool) -> Result<()> {
self.ensure_writable()?;
let ret = unsafe {
vips_sys::vips_draw_circle1(
self.c.as_ptr(),
ink,
cx,
cy,
r,
c"fill".as_ptr(),
fill as i32,
null() as *const c_char,
)
};
result_draw(ret)
}
pub fn draw_flood(&mut self, ink: &[f64], x: i32, y: i32) -> Result<()> {
self.ensure_writable()?;
let ret = unsafe {
vips_sys::vips_draw_flood(
self.c.as_ptr(),
ink.as_ptr() as *mut f64,
ink.len() as i32,
x,
y,
null() as *const c_char,
)
};
result_draw(ret)
}
pub fn draw_flood1(&mut self, ink: f64, x: i32, y: i32) -> Result<()> {
self.ensure_writable()?;
let ret = unsafe {
vips_sys::vips_draw_flood1(self.c.as_ptr(), ink, x, y, null() as *const c_char)
};
result_draw(ret)
}
pub fn draw_smudge(&mut self, left: u32, top: u32, width: u32, height: u32) -> Result<()> {
self.ensure_writable()?;
let ret = unsafe {
vips_sys::vips_draw_smudge(
self.c.as_ptr(),
left as i32,
top as i32,
width as i32,
height as i32,
null() as *const c_char,
)
};
result_draw(ret)
}
//
// ─── MOSAIC ─────────────────────────────────────────────────────────────────────
//
pub fn merge(
&self,
another: &VipsImage<'a>,
direction: VipsDirection,
dx: i32,
dy: i32,
mblend: Option<i32>,
) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
let ret = unsafe {
match mblend {
Some(mblend) => vips_sys::vips_merge(
self.c.as_ptr(),
another.as_ptr(),
&mut out_ptr,
direction,
dx,
dy,
c"mblend".as_ptr(),
mblend,
null() as *const c_char,
),
None => vips_sys::vips_merge(
self.c.as_ptr(),
another.as_ptr(),
&mut out_ptr,
direction,
dx,
dy,
null() as *const c_char,
),
}
};
result_with_ret(out_ptr, ret)
}
#[allow(clippy::too_many_arguments)]
pub fn mosaic(
&self,
sec: &VipsImage<'a>,
direction: VipsDirection,
xref: i32,
yref: i32,
xsec: i32,
ysec: i32,
bandno: Option<i32>,
hwindow: Option<i32>,
harea: Option<i32>,
mblend: Option<i32>,
) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
let ret = unsafe {
vips_sys::vips_mosaic(
self.c.as_ptr(),
sec.as_ptr(),
&mut out_ptr,
direction,
xref,
yref,
xsec,
ysec,
c"bandno".as_ptr(),
bandno.unwrap_or(-1),
c"hwindow".as_ptr(),
hwindow.unwrap_or(5),
c"harea".as_ptr(),
harea.unwrap_or(2),
c"mblend".as_ptr(),
mblend.unwrap_or(-1),
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}
#[allow(clippy::too_many_arguments)]
pub fn mosaic1(
&self,
sec: &VipsImage<'a>,
direction: VipsDirection,
xr1: i32,
yr1: i32,
xs1: i32,
ys1: i32,
xr2: i32,
yr2: i32,
xs2: i32,
ys2: i32,
search: Option<bool>,
hwindow: Option<i32>,
harea: Option<i32>,
interpolate: Option<VipsInterpolate>,
mblend: Option<i32>,
bandno: Option<i32>,
) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
let ret = unsafe {
match interpolate {
Some(interpolate) => vips_sys::vips_mosaic1(
self.c.as_ptr(),
sec.as_ptr(),
&mut out_ptr,
direction,
xr1,
yr1,
xs1,
ys1,
xr2,
yr2,
xs2,
ys2,
c"search".as_ptr(),
search.unwrap_or(false) as i32,
c"hwindow".as_ptr(),
hwindow.unwrap_or(5),
c"harea".as_ptr(),
harea.unwrap_or(2),
c"interpolate".as_ptr(),
interpolate.as_ptr(),
c"mblend".as_ptr(),
mblend.unwrap_or(-1),
c"bandno".as_ptr(),
bandno.unwrap_or(-1),
null() as *const c_char,
),
None => vips_sys::vips_mosaic1(
self.c.as_ptr(),
sec.as_ptr(),
&mut out_ptr,
direction,
xr1,
yr1,
xs1,
ys1,
xr2,
yr2,
xs2,
ys2,
c"search".as_ptr(),
search.unwrap_or(false) as i32,
c"hwindow".as_ptr(),
hwindow.unwrap_or(5),
c"harea".as_ptr(),
harea.unwrap_or(2),
c"mblend".as_ptr(),
mblend.unwrap_or(-1),
c"bandno".as_ptr(),
bandno.unwrap_or(-1),
null() as *const c_char,
),
}
};
result_with_ret(out_ptr, ret)
}
#[allow(clippy::too_many_arguments)]
pub fn match_(
&self,
sec: &VipsImage<'a>,
xr1: i32,
yr1: i32,
xs1: i32,
ys1: i32,
xr2: i32,
yr2: i32,
xs2: i32,
ys2: i32,
search: Option<bool>,
hwindow: Option<i32>,
harea: Option<i32>,
interpolate: Option<VipsInterpolate>,
) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
let ret = unsafe {
match interpolate {
Some(interpolate) => vips_sys::vips_match(
self.c.as_ptr(),
sec.as_ptr(),
&mut out_ptr,
xr1,
yr1,
xs1,
ys1,
xr2,
yr2,
xs2,
ys2,
c"search".as_ptr(),
search.unwrap_or(false) as i32,
c"hwindow".as_ptr(),
hwindow.unwrap_or(5),
c"harea".as_ptr(),
harea.unwrap_or(2),
c"interpolate".as_ptr(),
interpolate.as_ptr(),
null() as *const c_char,
),
None => vips_sys::vips_match(
self.c.as_ptr(),
sec.as_ptr(),
&mut out_ptr,
xr1,
yr1,
xs1,
ys1,
xr2,
yr2,
xs2,
ys2,
c"search".as_ptr(),
search.unwrap_or(false) as i32,
c"hwindow".as_ptr(),
hwindow.unwrap_or(5),
c"harea".as_ptr(),
harea.unwrap_or(2),
null() as *const c_char,
),
}
};
result_with_ret(out_ptr, ret)
}
pub fn globalbalance(
&self,
gamma: Option<f64>,
int_output: Option<bool>,
) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
let ret = unsafe {
vips_sys::vips_globalbalance(
self.c.as_ptr(),
&mut out_ptr,
c"gamma".as_ptr(),
gamma.unwrap_or(1.6),
c"int_output".as_ptr(),
int_output.unwrap_or(false) as i32,
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}
pub fn remosaic(&self, old_str: &str, new_str: &str) -> Result<VipsImage<'a>> {
let old_str = CString::new(old_str)
.map_err(|e| Error::InitFailed(format!("invalid old_str: {e}")))?;
let new_str = CString::new(new_str)
.map_err(|e| Error::InitFailed(format!("invalid new_str: {e}")))?;
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
let ret = unsafe {
vips_sys::vips_remosaic(
self.c.as_ptr(),
&mut out_ptr,
old_str.as_ptr(),
new_str.as_ptr(),
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}
//
// ─── PROPERTIES ─────────────────────────────────────────────────────────────────
//
/// Image width in pixels.
#[inline]
pub fn width(&self) -> u32 {
// SAFETY: `c` is a live image owned by `self`.
unsafe { (*self.c.as_ptr()).Xsize as u32 }
}
/// Image height in pixels.
#[inline]
pub fn height(&self) -> u32 {
// SAFETY: `c` is a live image owned by `self`.
unsafe { (*self.c.as_ptr()).Ysize as u32 }
}
/// Image dimensions as `(width, height)`.
#[inline]
pub fn size(&self) -> (u32, u32) {
(self.width(), self.height())
}
/// Number of bands (channels).
#[inline]
pub fn bands(&self) -> u32 {
// SAFETY: `c` is a live image owned by `self`.
unsafe { (*self.c.as_ptr()).Bands as u32 }
}
//
// ─── RESIZE ─────────────────────────────────────────────────────────────────────
//
/// Create a thumbnail from already-decoded pixels (`vips_thumbnail_image`).
///
/// Use this only when the source is already a live image (e.g. from
/// [`Self::from_memory`]). For files prefer [`Self::thumbnail_file`], and
/// for encoded buffers prefer [`Self::thumbnail_buffer`]: those combine
/// load + resize so libvips can shrink-on-load (faster, lower peak memory,
/// better quality). See the [libvips developer checklist](https://www.libvips.org/API/current/developer-checklist.html#performance).
///
/// # Arguments
/// * `width` - The desired width of the thumbnail.
/// * `height` - The desired height of the thumbnail.
/// * `size` - The size mode for the thumbnail (e.g., `VIPS_SIZE_BOTH`, `VIPS_SIZE_UP`, etc.).
///
/// # Errors
/// Returns an error if the thumbnail creation fails.
///
/// # Example
/// ```no_run
/// use vips::*;
///
/// fn main() -> Result<()> {
/// let _instance = VipsInstance::new("app_test", true)?;
/// let pixels = vec![0u8; 256 * 256 * 3];
/// let img = VipsImage::from_memory(pixels, 256, 256, 3, VipsBandFormat::VIPS_FORMAT_UCHAR)?;
/// let thumb = img.thumbnail(100, 100, VipsSize::VIPS_SIZE_BOTH)?;
/// thumb.write_to_file("thumb.jpg")?;
/// Ok(())
/// }
/// ```
pub fn thumbnail(&self, width: u32, height: u32, size: VipsSize) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
let ret = unsafe {
vips_sys::vips_thumbnail_image(
self.c.as_ptr(),
&mut out_ptr,
width as i32,
c"height".as_ptr(),
height as i32,
c"size".as_ptr(),
size,
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}
/// Create a thumbnail directly from a file path (`vips_thumbnail`).
///
/// Preferred for file sources: load and resize are combined so libvips can
/// use format shrink-on-load (JPEG/PNG/WebP/etc.). Typically several times
/// faster and far lower peak memory than `from_file` + [`Self::thumbnail`].
///
/// # Arguments
/// * `path` - Path to the source image.
/// * `width` - Target thumbnail width.
/// * `height` - Target thumbnail height.
/// * `size` - Fit mode (`VIPS_SIZE_BOTH`, `VIPS_SIZE_DOWN`, `VIPS_SIZE_UP`, `VIPS_SIZE_FORCE`).
///
/// # Errors
/// Returns an error if the file cannot be loaded or thumbnailing fails.
///
/// # Example
/// ```no_run
/// use vips::*;
///
/// fn main() -> Result<()> {
/// let _instance = VipsInstance::new("app_test", true)?;
/// let thumb = VipsImage::thumbnail_file("input.jpg", 256, 256, VipsSize::VIPS_SIZE_BOTH)?;
/// thumb.write_to_file("thumb.jpg")?;
/// Ok(())
/// }
/// ```
pub fn thumbnail_file(
path: impl AsRef<Path>,
width: u32,
height: u32,
size: VipsSize,
) -> Result<VipsImage<'static>> {
let path = path_to_cstring(path.as_ref())?;
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: path is a valid C string; out is written by libvips on success.
let ret = unsafe {
vips_sys::vips_thumbnail(
path.as_ptr(),
&mut out_ptr,
width as c_int,
c"height".as_ptr(),
height as c_int,
c"size".as_ptr(),
size,
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}
/// Create a thumbnail from an encoded image buffer (`vips_thumbnail_buffer`).
///
/// Preferred for in-memory file contents (JPEG/PNG/WebP/… bytes): combines
/// decode + resize so libvips can shrink-on-load. Prefer this over
/// `from_buffer` + [`Self::thumbnail`].
///
/// The returned image may retain a lazy load pipeline that reads from
/// `buf`; keep the buffer alive until the thumbnail is fully consumed.
///
/// # Arguments
/// * `buf` - Encoded image bytes.
/// * `width` - Target thumbnail width.
/// * `height` - Target thumbnail height.
/// * `size` - Fit mode.
///
/// # Errors
/// Returns an error if the buffer is not a valid image or thumbnailing fails.
///
/// # Example
/// ```no_run
/// use vips::*;
///
/// fn main() -> Result<()> {
/// let _instance = VipsInstance::new("app_test", true)?;
/// let bytes = std::fs::read("input.jpg")?;
/// let thumb = VipsImage::thumbnail_buffer(&bytes, 256, 256, VipsSize::VIPS_SIZE_BOTH)?;
/// thumb.write_to_file("thumb.jpg")?;
/// Ok(())
/// }
/// ```
pub fn thumbnail_buffer(
buf: &'a [u8],
width: u32,
height: u32,
size: VipsSize,
) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: buf comes from a valid Rust slice; out is written by libvips.
let ret = unsafe {
vips_sys::vips_thumbnail_buffer(
buf.as_ptr() as *mut c_void,
buf.len(),
&mut out_ptr,
width as c_int,
c"height".as_ptr(),
height as c_int,
c"size".as_ptr(),
size,
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}
/// Resize the image.
///
/// # Arguments
/// * `scale` - The scaling factor for the horizontal dimension.
/// * `vscale` - Optional scaling factor for the vertical dimension. If not provided, it defaults to the value of `scale`.
/// * `kernel` - Optional kernel to use for resizing. If not provided, it defaults to `VIPS_KERNEL_LANCZOS3`.
///
/// # Returns
/// A `Result` containing the resized `VipsImage` or an error.
///
/// # Errors
/// Returns an error if the resizing operation fails.
///
/// # Example
/// ```no_run
/// use vips::*;
///
/// fn main() -> Result<()> {
/// let _instance = VipsInstance::new("app_test", true)?;
/// let img = VipsImage::from_file("input.jpg")?;
/// let resized_img = img.resize(0.5, None, None)?;
/// resized_img.write_to_file("resized.jpg")?;
/// Ok(())
/// }
/// ```
pub fn resize(
&self,
scale: f64,
vscale: Option<f64>,
kernel: Option<VipsKernel>,
) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
let ret = unsafe {
vips_sys::vips_resize(
self.c.as_ptr(),
&mut out_ptr,
scale,
c"vscale".as_ptr(),
vscale.unwrap_or(scale),
c"kernel".as_ptr(),
kernel.unwrap_or(VipsKernel::VIPS_KERNEL_LANCZOS3),
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}
/// Large-downscale helper: box pre-shrink then `resize`.
///
/// libvips recommends shrinking by an integer factor with a box filter
/// before the final kernel resample. For small images the extra pass
/// costs more than it saves, so this falls back to plain `resize`.
pub fn resize_reduce(
&self,
scale: f64,
vscale: Option<f64>,
kernel: Option<VipsKernel>,
) -> Result<VipsImage<'a>> {
let vscale = vscale.unwrap_or(scale);
if scale >= 1.0 && vscale >= 1.0 {
return self.resize(scale, Some(vscale), kernel);
}
let hscale = scale.max(f64::EPSILON);
let vscale = vscale.max(f64::EPSILON);
let pixels = self.width() as u64 * self.height() as u64;
// Pre-shrink only pays off on large sources.
if pixels < 4_000_000 {
return self.resize(hscale, Some(vscale), kernel);
}
let hshrink = if hscale < 0.5 {
(1.0 / hscale / 2.0).floor().max(1.0)
} else {
1.0
};
let vshrink = if vscale < 0.5 {
(1.0 / vscale / 2.0).floor().max(1.0)
} else {
1.0
};
let pre = if hshrink > 1.0 || vshrink > 1.0 {
Some(self.shrink_box(hshrink, vshrink)?)
} else {
None
};
let base = pre.as_ref().unwrap_or(self);
base.resize(hscale * hshrink, Some(vscale * vshrink), kernel)
}
/// Integer box shrink (`vips_shrink`) — cheapest pre-pass for large downscale.
pub fn shrink_box(&self, xshrink: f64, yshrink: f64) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
let ret = unsafe {
vips_sys::vips_shrink(
self.c.as_ptr(),
&mut out_ptr,
xshrink,
yshrink,
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}
/// Low-level reduce (shrink by a floating factor using a kernel).
pub fn reduce(
&self,
hshrink: f64,
vshrink: f64,
kernel: Option<VipsKernel>,
centre: Option<bool>,
) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
let ret = unsafe {
vips_sys::vips_reduce(
self.c.as_ptr(),
&mut out_ptr,
hshrink,
vshrink,
c"kernel".as_ptr(),
kernel.unwrap_or(VipsKernel::VIPS_KERNEL_LANCZOS3),
c"centre".as_ptr(),
centre.unwrap_or(false) as i32,
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}
//
// ─── GEOMETRY ──────────────────────────────────────────────────────────────────
//
/// Crop a rectangle (`left`, `top`, `width`, `height`).
pub fn crop(&self, left: i32, top: i32, width: i32, height: i32) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image; libvips writes a new owned out image.
let ret = unsafe {
vips_sys::vips_crop(
self.c.as_ptr(),
&mut out_ptr,
left,
top,
width,
height,
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}
/// Alias of [`Self::crop`] (`vips_extract_area`).
#[inline]
pub fn extract_area(
&self,
left: i32,
top: i32,
width: i32,
height: i32,
) -> Result<VipsImage<'a>> {
self.crop(left, top, width, height)
}
/// Embed the image in a larger canvas at `(x, y)`.
pub fn embed(
&self,
x: i32,
y: i32,
width: i32,
height: i32,
extend: Option<VipsExtend>,
) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image; optional extend key defaults to black when omitted.
let ret = unsafe {
vips_sys::vips_embed(
self.c.as_ptr(),
&mut out_ptr,
x,
y,
width,
height,
c"extend".as_ptr(),
extend.unwrap_or(VipsExtend::VIPS_EXTEND_BLACK),
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}
/// Place the image inside a larger canvas using a compass direction.
pub fn gravity(
&self,
direction: VipsCompassDirection,
width: i32,
height: i32,
extend: Option<VipsExtend>,
) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image; optional extend key defaults to black.
let ret = unsafe {
vips_sys::vips_gravity(
self.c.as_ptr(),
&mut out_ptr,
direction,
width,
height,
c"extend".as_ptr(),
extend.unwrap_or(VipsExtend::VIPS_EXTEND_BLACK),
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}
/// Insert `sub` into a copy of `self` at `(x, y)`.
pub fn insert(&self, sub: &VipsImage<'a>, x: i32, y: i32) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: both images live for the call.
let ret = unsafe {
vips_sys::vips_insert(
self.c.as_ptr(),
sub.as_ptr(),
&mut out_ptr,
x,
y,
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}
/// Flip about a horizontal or vertical axis.
pub fn flip(&self, direction: VipsDirection) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret = unsafe {
vips_sys::vips_flip(
self.c.as_ptr(),
&mut out_ptr,
direction,
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}
/// Flip horizontally.
#[inline]
pub fn fliphor(&self) -> Result<VipsImage<'a>> {
self.flip(VipsDirection::VIPS_DIRECTION_HORIZONTAL)
}
/// Flip vertically.
#[inline]
pub fn flipver(&self) -> Result<VipsImage<'a>> {
self.flip(VipsDirection::VIPS_DIRECTION_VERTICAL)
}
/// Rotate by a multiple of 90°.
pub fn rot(&self, angle: vips_sys::VipsAngle) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret = unsafe {
vips_sys::vips_rot(
self.c.as_ptr(),
&mut out_ptr,
angle,
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}
/// Rotate 90° clockwise.
#[inline]
pub fn rot90(&self) -> Result<VipsImage<'a>> {
self.rot(vips_sys::VipsAngle::VIPS_ANGLE_D90)
}
/// Rotate 180°.
#[inline]
pub fn rot180(&self) -> Result<VipsImage<'a>> {
self.rot(vips_sys::VipsAngle::VIPS_ANGLE_D180)
}
/// Rotate 270° clockwise.
#[inline]
pub fn rot270(&self) -> Result<VipsImage<'a>> {
self.rot(vips_sys::VipsAngle::VIPS_ANGLE_D270)
}
/// Rotate by an arbitrary angle in degrees (affine).
pub fn rotate(&self, angle: f64) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret = unsafe {
vips_sys::vips_rotate(
self.c.as_ptr(),
&mut out_ptr,
angle,
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}
/// Rotate according to EXIF orientation tag.
pub fn autorot(&self) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret = unsafe {
vips_sys::vips_autorot(self.c.as_ptr(), &mut out_ptr, null() as *const c_char)
};
result_with_ret(out_ptr, ret)
}
/// Integer zoom (nearest-neighbour scale).
pub fn zoom(&self, xfac: i32, yfac: i32) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret = unsafe {
vips_sys::vips_zoom(
self.c.as_ptr(),
&mut out_ptr,
xfac,
yfac,
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}
/// Extract a single band.
pub fn extract_band(&self, band: i32) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret = unsafe {
vips_sys::vips_extract_band(
self.c.as_ptr(),
&mut out_ptr,
band,
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}
/// Join with another image band-wise.
pub fn bandjoin2(&self, other: &VipsImage<'a>) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: both images live for the call.
let ret = unsafe {
vips_sys::vips_bandjoin2(
self.c.as_ptr(),
other.as_ptr(),
&mut out_ptr,
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}
/// Append constant bands (e.g. alpha = 255).
pub fn bandjoin_const(&self, constants: &[f64]) -> Result<VipsImage<'a>> {
if constants.is_empty() {
return self.copy();
}
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: `constants` is a valid contiguous f64 buffer for `n` bands.
let ret = unsafe {
vips_sys::vips_bandjoin_const(
self.c.as_ptr(),
&mut out_ptr,
constants.as_ptr() as *mut f64,
constants.len() as i32,
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}
/// Materialize a memory image (end a sequential pipeline). libvips may
/// share existing memory storage; safe drawing detaches it when needed.
pub fn copy_memory(&self) -> Result<VipsImage<'a>> {
// SAFETY: live image; libvips returns a new owned memory image.
let ptr = unsafe { vips_sys::vips_image_copy_memory(self.c.as_ptr()) };
result(ptr)
}
/// Copy with optional metadata overrides (format, interpretation, …).
pub fn copy(&self) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret =
unsafe { vips_sys::vips_copy(self.c.as_ptr(), &mut out_ptr, null() as *const c_char) };
result_with_ret(out_ptr, ret)
}
//
// ─── ARITHMETIC / COLOR / FILTER ──────────────────────────────────────────────
//
/// Pixel-wise add of two images.
pub fn add(&self, other: &VipsImage<'a>) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: both images live for the call.
let ret = unsafe {
vips_sys::vips_add(
self.c.as_ptr(),
other.as_ptr(),
&mut out_ptr,
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}
/// Pixel-wise subtract.
pub fn subtract(&self, other: &VipsImage<'a>) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: both images live for the call.
let ret = unsafe {
vips_sys::vips_subtract(
self.c.as_ptr(),
other.as_ptr(),
&mut out_ptr,
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}
/// Pixel-wise multiply.
pub fn multiply(&self, other: &VipsImage<'a>) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: both images live for the call.
let ret = unsafe {
vips_sys::vips_multiply(
self.c.as_ptr(),
other.as_ptr(),
&mut out_ptr,
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}
/// Pixel-wise divide.
pub fn divide(&self, other: &VipsImage<'a>) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: both images live for the call.
let ret = unsafe {
vips_sys::vips_divide(
self.c.as_ptr(),
other.as_ptr(),
&mut out_ptr,
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}
/// Affine intensity transform: `out = a * in + b`.
pub fn linear1(&self, a: f64, b: f64) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret = unsafe {
vips_sys::vips_linear1(self.c.as_ptr(), &mut out_ptr, a, b, null() as *const c_char)
};
result_with_ret(out_ptr, ret)
}
/// Per-band affine intensity transform (`a[i] * in + b[i]`).
pub fn linear(&self, a: &[f64], b: &[f64]) -> Result<VipsImage<'a>> {
if a.is_empty() || a.len() != b.len() || a.len() > i32::MAX as usize {
return Err(Error::Other(
"linear requires equal nonempty a/b arrays with an i32 length".into(),
));
}
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: equal-length contiguous buffers for n bands.
let ret = unsafe {
vips_sys::vips_linear(
self.c.as_ptr(),
&mut out_ptr,
a.as_ptr(),
b.as_ptr(),
a.len() as i32,
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}
/// Photometric negative (`max - in` for unsigned formats).
pub fn invert(&self) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret = unsafe {
vips_sys::vips_invert(self.c.as_ptr(), &mut out_ptr, null() as *const c_char)
};
result_with_ret(out_ptr, ret)
}
/// Cast to another band format.
pub fn cast(&self, format: VipsBandFormat) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret = unsafe {
vips_sys::vips_cast(
self.c.as_ptr(),
&mut out_ptr,
format,
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}
/// Convert colour space (e.g. sRGB ↔ scRGB ↔ Lab).
pub fn colourspace(
&self,
interpretation: vips_sys::VipsInterpretation,
) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret = unsafe {
vips_sys::vips_colourspace(
self.c.as_ptr(),
&mut out_ptr,
interpretation,
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}
/// Gaussian blur.
pub fn gaussblur(&self, sigma: f64) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret = unsafe {
vips_sys::vips_gaussblur(
self.c.as_ptr(),
&mut out_ptr,
sigma,
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}
/// Unsharp-mask sharpen.
pub fn sharpen(&self, sigma: f64) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret = unsafe {
vips_sys::vips_sharpen(
self.c.as_ptr(),
&mut out_ptr,
c"sigma".as_ptr(),
sigma,
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}
//
// ─── STATISTICS ───────────────────────────────────────────────────────────────
//
/// Average of all pixels.
pub fn avg(&self) -> Result<f64> {
let mut out: f64 = 0.0;
// SAFETY: live image; out is written by libvips.
let ret = unsafe { vips_sys::vips_avg(self.c.as_ptr(), &mut out, null() as *const c_char) };
ffi::ret_to_result(ret)?;
Ok(out)
}
/// Minimum pixel value.
pub fn min_value(&self) -> Result<f64> {
let mut out: f64 = 0.0;
// SAFETY: live image; out is written by libvips.
let ret = unsafe { vips_sys::vips_min(self.c.as_ptr(), &mut out, null() as *const c_char) };
ffi::ret_to_result(ret)?;
Ok(out)
}
/// Maximum pixel value.
pub fn max_value(&self) -> Result<f64> {
let mut out: f64 = 0.0;
// SAFETY: live image; out is written by libvips.
let ret = unsafe { vips_sys::vips_max(self.c.as_ptr(), &mut out, null() as *const c_char) };
ffi::ret_to_result(ret)?;
Ok(out)
}
/// Pixel values at `(x, y)` as a `Vec<f64>` (one entry per band).
pub fn getpoint(&self, x: i32, y: i32) -> Result<Vec<f64>> {
let mut vector: *mut f64 = null_mut();
let mut n: c_int = 0;
// SAFETY: live image; libvips allocates `vector` of length `n`.
let ret = unsafe {
vips_sys::vips_getpoint(
self.c.as_ptr(),
&mut vector,
&mut n,
x,
y,
null() as *const c_char,
)
};
ffi::ret_to_result(ret)?;
if vector.is_null() || n <= 0 {
return Ok(Vec::new());
}
// SAFETY: non-null buffer of `n` doubles owned by us; free with g_free.
let values = unsafe {
let slice = std::slice::from_raw_parts(vector as *const f64, n as usize);
let owned = slice.to_vec();
vips_sys::g_free(vector.cast());
owned
};
Ok(values)
}
/// Standard deviation of all pixels.
pub fn deviate(&self) -> Result<f64> {
let mut out: f64 = 0.0;
// SAFETY: live image; out is written by libvips.
let ret =
unsafe { vips_sys::vips_deviate(self.c.as_ptr(), &mut out, null() as *const c_char) };
ffi::ret_to_result(ret)?;
Ok(out)
}
/// Threshold at percentile `percent` of the image histogram (0–100).
pub fn percent(&self, percent: f64) -> Result<i32> {
let mut threshold: c_int = 0;
// SAFETY: live image; threshold is written by libvips.
let ret = unsafe {
vips_sys::vips_percent(
self.c.as_ptr(),
percent,
&mut threshold,
null() as *const c_char,
)
};
ffi::ret_to_result(ret)?;
Ok(threshold)
}
/// Bounds of non-background pixels as `(left, top, width, height)`.
pub fn find_trim(
&self,
threshold: Option<f64>,
background: Option<&[f64]>,
) -> Result<(i32, i32, i32, i32)> {
let mut left = 0;
let mut top = 0;
let mut width = 0;
let mut height = 0;
// SAFETY: live image; out integers written by libvips.
// Optional keys omitted when None so libvips defaults apply.
let ret = unsafe {
match (threshold, background) {
(Some(t), Some(bg)) => vips_sys::vips_find_trim(
self.c.as_ptr(),
&mut left,
&mut top,
&mut width,
&mut height,
c"threshold".as_ptr(),
t,
c"background".as_ptr(),
bg.as_ptr() as *mut f64,
bg.len() as i32,
null() as *const c_char,
),
(Some(t), None) => vips_sys::vips_find_trim(
self.c.as_ptr(),
&mut left,
&mut top,
&mut width,
&mut height,
c"threshold".as_ptr(),
t,
null() as *const c_char,
),
(None, Some(bg)) => vips_sys::vips_find_trim(
self.c.as_ptr(),
&mut left,
&mut top,
&mut width,
&mut height,
c"background".as_ptr(),
bg.as_ptr() as *mut f64,
bg.len() as i32,
null() as *const c_char,
),
(None, None) => vips_sys::vips_find_trim(
self.c.as_ptr(),
&mut left,
&mut top,
&mut width,
&mut height,
null() as *const c_char,
),
}
};
ffi::ret_to_result(ret)?;
Ok((left, top, width, height))
}
//
// ─── MATH / RELATIONAL / BOOLEAN (lua-vips convenience style) ─────────────────
//
/// Apply a math op (`sin`, `cos`, `log`, …).
pub fn math(&self, op: vips_sys::VipsOperationMath) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret = unsafe {
vips_sys::vips_math(self.c.as_ptr(), &mut out_ptr, op, null() as *const c_char)
};
result_with_ret(out_ptr, ret)
}
/// Sine (degrees).
#[inline]
pub fn sin(&self) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret =
unsafe { vips_sys::vips_sin(self.c.as_ptr(), &mut out_ptr, null() as *const c_char) };
result_with_ret(out_ptr, ret)
}
/// Cosine (degrees).
#[inline]
pub fn cos(&self) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret =
unsafe { vips_sys::vips_cos(self.c.as_ptr(), &mut out_ptr, null() as *const c_char) };
result_with_ret(out_ptr, ret)
}
/// Tangent (degrees).
#[inline]
pub fn tan(&self) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret =
unsafe { vips_sys::vips_tan(self.c.as_ptr(), &mut out_ptr, null() as *const c_char) };
result_with_ret(out_ptr, ret)
}
/// Natural logarithm.
#[inline]
pub fn ln(&self) -> Result<VipsImage<'a>> {
self.math(vips_sys::VipsOperationMath::VIPS_OPERATION_MATH_LOG)
}
/// Base-10 logarithm.
#[inline]
pub fn log10(&self) -> Result<VipsImage<'a>> {
self.math(vips_sys::VipsOperationMath::VIPS_OPERATION_MATH_LOG10)
}
/// e^pixel.
#[inline]
pub fn exp(&self) -> Result<VipsImage<'a>> {
self.math(vips_sys::VipsOperationMath::VIPS_OPERATION_MATH_EXP)
}
/// 10^pixel.
#[inline]
pub fn exp10(&self) -> Result<VipsImage<'a>> {
self.math(vips_sys::VipsOperationMath::VIPS_OPERATION_MATH_EXP10)
}
/// Floor.
pub fn floor(&self) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret =
unsafe { vips_sys::vips_floor(self.c.as_ptr(), &mut out_ptr, null() as *const c_char) };
result_with_ret(out_ptr, ret)
}
/// Ceiling.
pub fn ceil(&self) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret =
unsafe { vips_sys::vips_ceil(self.c.as_ptr(), &mut out_ptr, null() as *const c_char) };
result_with_ret(out_ptr, ret)
}
/// Round to nearest integer.
pub fn rint(&self) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret =
unsafe { vips_sys::vips_rint(self.c.as_ptr(), &mut out_ptr, null() as *const c_char) };
result_with_ret(out_ptr, ret)
}
/// Absolute value.
pub fn abs(&self) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret =
unsafe { vips_sys::vips_abs(self.c.as_ptr(), &mut out_ptr, null() as *const c_char) };
result_with_ret(out_ptr, ret)
}
/// Sign of each pixel (-1, 0, +1).
pub fn sign(&self) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret =
unsafe { vips_sys::vips_sign(self.c.as_ptr(), &mut out_ptr, null() as *const c_char) };
result_with_ret(out_ptr, ret)
}
/// Clamp to the band format range.
pub fn clamp(&self) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret =
unsafe { vips_sys::vips_clamp(self.c.as_ptr(), &mut out_ptr, null() as *const c_char) };
result_with_ret(out_ptr, ret)
}
/// Raise each pixel to `exp`.
pub fn pow_const(&self, exp: f64) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret = unsafe {
vips_sys::vips_pow_const1(self.c.as_ptr(), &mut out_ptr, exp, null() as *const c_char)
};
result_with_ret(out_ptr, ret)
}
/// Relational compare with a constant → 255/0 mask.
pub fn relational_const(
&self,
op: vips_sys::VipsOperationRelational,
c: f64,
) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret = unsafe {
vips_sys::vips_relational_const1(
self.c.as_ptr(),
&mut out_ptr,
op,
c,
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}
/// `self < c` mask.
#[inline]
pub fn less(&self, c: f64) -> Result<VipsImage<'a>> {
self.relational_const(
vips_sys::VipsOperationRelational::VIPS_OPERATION_RELATIONAL_LESS,
c,
)
}
/// `self <= c` mask.
#[inline]
pub fn lesseq(&self, c: f64) -> Result<VipsImage<'a>> {
self.relational_const(
vips_sys::VipsOperationRelational::VIPS_OPERATION_RELATIONAL_LESSEQ,
c,
)
}
/// `self > c` mask.
#[inline]
pub fn more(&self, c: f64) -> Result<VipsImage<'a>> {
self.relational_const(
vips_sys::VipsOperationRelational::VIPS_OPERATION_RELATIONAL_MORE,
c,
)
}
/// `self >= c` mask.
#[inline]
pub fn moreeq(&self, c: f64) -> Result<VipsImage<'a>> {
self.relational_const(
vips_sys::VipsOperationRelational::VIPS_OPERATION_RELATIONAL_MOREEQ,
c,
)
}
/// `self == c` mask.
#[inline]
pub fn equal_const(&self, c: f64) -> Result<VipsImage<'a>> {
self.relational_const(
vips_sys::VipsOperationRelational::VIPS_OPERATION_RELATIONAL_EQUAL,
c,
)
}
/// `self != c` mask.
#[inline]
pub fn notequal_const(&self, c: f64) -> Result<VipsImage<'a>> {
self.relational_const(
vips_sys::VipsOperationRelational::VIPS_OPERATION_RELATIONAL_NOTEQ,
c,
)
}
/// Boolean op with a constant.
pub fn boolean_const(
&self,
op: vips_sys::VipsOperationBoolean,
c: f64,
) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret = unsafe {
vips_sys::vips_boolean_const1(
self.c.as_ptr(),
&mut out_ptr,
op,
c,
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}
/// Bitwise AND with constant.
#[inline]
pub fn and_const(&self, c: f64) -> Result<VipsImage<'a>> {
self.boolean_const(
vips_sys::VipsOperationBoolean::VIPS_OPERATION_BOOLEAN_AND,
c,
)
}
/// Bitwise OR with constant.
#[inline]
pub fn or_const(&self, c: f64) -> Result<VipsImage<'a>> {
self.boolean_const(vips_sys::VipsOperationBoolean::VIPS_OPERATION_BOOLEAN_OR, c)
}
/// Bitwise XOR with constant.
#[inline]
pub fn eor_const(&self, c: f64) -> Result<VipsImage<'a>> {
self.boolean_const(
vips_sys::VipsOperationBoolean::VIPS_OPERATION_BOOLEAN_EOR,
c,
)
}
/// Bitwise left shift by constant.
pub fn lshift_const(&self, c: f64) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret = unsafe {
vips_sys::vips_lshift_const1(self.c.as_ptr(), &mut out_ptr, c, null() as *const c_char)
};
result_with_ret(out_ptr, ret)
}
/// Bitwise right shift by constant.
pub fn rshift_const(&self, c: f64) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret = unsafe {
vips_sys::vips_rshift_const1(self.c.as_ptr(), &mut out_ptr, c, null() as *const c_char)
};
result_with_ret(out_ptr, ret)
}
/// Collapse all bands with a boolean op (`and`/`or`/`eor`).
pub fn bandbool(&self, op: vips_sys::VipsOperationBoolean) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret = unsafe {
vips_sys::vips_bandbool(self.c.as_ptr(), &mut out_ptr, op, null() as *const c_char)
};
result_with_ret(out_ptr, ret)
}
/// Collapse bands with AND.
#[inline]
pub fn bandand(&self) -> Result<VipsImage<'a>> {
self.bandbool(vips_sys::VipsOperationBoolean::VIPS_OPERATION_BOOLEAN_AND)
}
/// Collapse bands with OR.
#[inline]
pub fn bandor(&self) -> Result<VipsImage<'a>> {
self.bandbool(vips_sys::VipsOperationBoolean::VIPS_OPERATION_BOOLEAN_OR)
}
/// Collapse bands with XOR.
#[inline]
pub fn bando(&self) -> Result<VipsImage<'a>> {
self.bandbool(vips_sys::VipsOperationBoolean::VIPS_OPERATION_BOOLEAN_EOR)
}
/// Mean of each pixel across bands → 1-band image.
pub fn bandmean(&self) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret = unsafe {
vips_sys::vips_bandmean(self.c.as_ptr(), &mut out_ptr, null() as *const c_char)
};
result_with_ret(out_ptr, ret)
}
/// Split into one single-band image per band.
pub fn bandsplit(&self) -> Result<Vec<VipsImage<'a>>> {
let n = self.bands() as i32;
let mut out = Vec::with_capacity(n as usize);
for band in 0..n {
out.push(self.extract_band(band)?);
}
Ok(out)
}
//
// ─── FILTER / MORPH / EDGE ────────────────────────────────────────────────────
//
/// Convolve with a mask image.
pub fn conv(&self, mask: &VipsImage<'a>) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: both images live for the call.
let ret = unsafe {
vips_sys::vips_conv(
self.c.as_ptr(),
&mut out_ptr,
mask.as_ptr(),
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}
/// Morphological op with a structuring element.
pub fn morph(
&self,
mask: &VipsImage<'a>,
op: vips_sys::VipsOperationMorphology,
) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: both images live for the call.
let ret = unsafe {
vips_sys::vips_morph(
self.c.as_ptr(),
&mut out_ptr,
mask.as_ptr(),
op,
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}
/// Erode with structuring element.
#[inline]
pub fn erode(&self, mask: &VipsImage<'a>) -> Result<VipsImage<'a>> {
self.morph(
mask,
vips_sys::VipsOperationMorphology::VIPS_OPERATION_MORPHOLOGY_ERODE,
)
}
/// Dilate with structuring element.
#[inline]
pub fn dilate(&self, mask: &VipsImage<'a>) -> Result<VipsImage<'a>> {
self.morph(
mask,
vips_sys::VipsOperationMorphology::VIPS_OPERATION_MORPHOLOGY_DILATE,
)
}
/// Rank filter (median when `index = w*h/2`).
pub fn rank(&self, width: i32, height: i32, index: i32) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret = unsafe {
vips_sys::vips_rank(
self.c.as_ptr(),
&mut out_ptr,
width,
height,
index,
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}
/// `size × size` median filter.
#[inline]
pub fn median(&self, size: i32) -> Result<VipsImage<'a>> {
let area = size.checked_mul(size).filter(|_| size > 0).ok_or_else(|| {
Error::Other("median size must be positive and its square must fit i32".into())
})?;
let index = area / 2;
self.rank(size, size, index)
}
/// Sobel edge magnitude.
pub fn sobel(&self) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret =
unsafe { vips_sys::vips_sobel(self.c.as_ptr(), &mut out_ptr, null() as *const c_char) };
result_with_ret(out_ptr, ret)
}
/// Canny edge detector.
pub fn canny(&self, sigma: Option<f64>) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret = unsafe {
match sigma {
Some(s) => vips_sys::vips_canny(
self.c.as_ptr(),
&mut out_ptr,
c"sigma".as_ptr(),
s,
null() as *const c_char,
),
None => {
vips_sys::vips_canny(self.c.as_ptr(), &mut out_ptr, null() as *const c_char)
}
}
};
result_with_ret(out_ptr, ret)
}
//
// ─── LOGIC / CROP / COLOR extras ──────────────────────────────────────────────
//
/// Pick pixels from `then` or `else` using this image as a 0/non-zero mask.
pub fn ifthenelse(&self, then: &VipsImage<'a>, els: &VipsImage<'a>) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: all three images live for the call.
let ret = unsafe {
vips_sys::vips_ifthenelse(
self.c.as_ptr(),
then.as_ptr(),
els.as_ptr(),
&mut out_ptr,
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}
/// Attention-based crop to `width`×`height`.
pub fn smartcrop(
&self,
width: i32,
height: i32,
interesting: Option<VipsInteresting>,
) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image; optional interesting key omitted when None.
let ret = unsafe {
match interesting {
Some(i) => vips_sys::vips_smartcrop(
self.c.as_ptr(),
&mut out_ptr,
width,
height,
c"interesting".as_ptr(),
i,
null() as *const c_char,
),
None => vips_sys::vips_smartcrop(
self.c.as_ptr(),
&mut out_ptr,
width,
height,
null() as *const c_char,
),
}
};
result_with_ret(out_ptr, ret)
}
/// False-colour visualisation.
pub fn falsecolour(&self) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret = unsafe {
vips_sys::vips_falsecolour(self.c.as_ptr(), &mut out_ptr, null() as *const c_char)
};
result_with_ret(out_ptr, ret)
}
/// Premultiply alpha.
pub fn premultiply(&self, max_alpha: Option<f64>) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret = unsafe {
match max_alpha {
Some(m) => vips_sys::vips_premultiply(
self.c.as_ptr(),
&mut out_ptr,
c"max-alpha".as_ptr(),
m,
null() as *const c_char,
),
None => vips_sys::vips_premultiply(
self.c.as_ptr(),
&mut out_ptr,
null() as *const c_char,
),
}
};
result_with_ret(out_ptr, ret)
}
/// Undo premultiply.
pub fn unpremultiply(&self, max_alpha: Option<f64>) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret = unsafe {
match max_alpha {
Some(m) => vips_sys::vips_unpremultiply(
self.c.as_ptr(),
&mut out_ptr,
c"max-alpha".as_ptr(),
m,
null() as *const c_char,
),
None => vips_sys::vips_unpremultiply(
self.c.as_ptr(),
&mut out_ptr,
null() as *const c_char,
),
}
};
result_with_ret(out_ptr, ret)
}
/// Sequential access hint (streaming pipelines).
pub fn sequential(&self) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret = unsafe {
vips_sys::vips_sequential(self.c.as_ptr(), &mut out_ptr, null() as *const c_char)
};
result_with_ret(out_ptr, ret)
}
/// Cut into tiles and wrap to a new sheet.
pub fn wrap(&self) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret =
unsafe { vips_sys::vips_wrap(self.c.as_ptr(), &mut out_ptr, null() as *const c_char) };
result_with_ret(out_ptr, ret)
}
/// Replicate the image `across`×`down` times.
pub fn replicate(&self, across: i32, down: i32) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret = unsafe {
vips_sys::vips_replicate(
self.c.as_ptr(),
&mut out_ptr,
across,
down,
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}
/// Reassemble a large image into a tiled grid.
pub fn grid(&self, tile_height: i32, across: i32, down: i32) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret = unsafe {
vips_sys::vips_grid(
self.c.as_ptr(),
&mut out_ptr,
tile_height,
across,
down,
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}
/// Copy through a temporary file (break a pipeline).
pub fn copy_file(&self) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret = unsafe {
vips_sys::vips_copy_file(self.c.as_ptr(), &mut out_ptr, null() as *const c_char)
};
result_with_ret(out_ptr, ret)
}
//
// ─── COLOR / HIST / EDGE extras ───────────────────────────────────────────────
//
/// Non-linear gamma encode/decode (`vips_gamma`).
pub fn gamma(&self, exponent: Option<f64>) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret = unsafe {
match exponent {
Some(e) => vips_sys::vips_gamma(
self.c.as_ptr(),
&mut out_ptr,
c"exponent".as_ptr(),
e,
null() as *const c_char,
),
None => {
vips_sys::vips_gamma(self.c.as_ptr(), &mut out_ptr, null() as *const c_char)
}
}
};
result_with_ret(out_ptr, ret)
}
/// One-band intensity histogram.
pub fn hist_find(&self) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret = unsafe {
vips_sys::vips_hist_find(self.c.as_ptr(), &mut out_ptr, null() as *const c_char)
};
result_with_ret(out_ptr, ret)
}
/// Local histogram equalisation.
pub fn hist_local(&self, width: i32, height: i32) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret = unsafe {
vips_sys::vips_hist_local(
self.c.as_ptr(),
&mut out_ptr,
width,
height,
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}
/// Global histogram equalisation.
pub fn hist_equal(&self) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret = unsafe {
vips_sys::vips_hist_equal(self.c.as_ptr(), &mut out_ptr, null() as *const c_char)
};
result_with_ret(out_ptr, ret)
}
/// Histogram entropy.
pub fn hist_entropy(&self) -> Result<f64> {
let mut out: f64 = 0.0;
// SAFETY: live image.
let ret = unsafe {
vips_sys::vips_hist_entropy(self.c.as_ptr(), &mut out, null() as *const c_char)
};
ffi::ret_to_result(ret)?;
Ok(out)
}
/// Map each pixel through a lookup table image.
pub fn maplut(&self, lut: &VipsImage<'a>) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: both images live for the call.
let ret = unsafe {
vips_sys::vips_maplut(
self.c.as_ptr(),
&mut out_ptr,
lut.as_ptr(),
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}
/// Fold bands into width (`band × n`).
pub fn bandfold(&self) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret = unsafe {
vips_sys::vips_bandfold(self.c.as_ptr(), &mut out_ptr, null() as *const c_char)
};
result_with_ret(out_ptr, ret)
}
/// Unfold width into bands.
pub fn bandunfold(&self) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image.
let ret = unsafe {
vips_sys::vips_bandunfold(self.c.as_ptr(), &mut out_ptr, null() as *const c_char)
};
result_with_ret(out_ptr, ret)
}
/// Label connected regions; returns a label mask image.
pub fn labelregions(&self) -> Result<VipsImage<'a>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: live image; mask out-param is the labelled image.
let ret = unsafe {
vips_sys::vips_labelregions(self.c.as_ptr(), &mut out_ptr, null() as *const c_char)
};
result_with_ret(out_ptr, ret)
}
//
// ─── IO ─────────────────────────────────────────────────────────────────────────
//
/// Write the image to `path`. Format is inferred from the extension.
pub fn write_to_file(&self, path: impl AsRef<Path>) -> Result<()> {
let path = path_to_cstring(path.as_ref())?;
let ret = unsafe {
vips_sys::vips_image_write_to_file(
self.c.as_ptr(),
path.as_ptr(),
null() as *const c_char,
)
};
result_draw(ret)
}
/// Export raw band-packed pixels into a freshly allocated `Vec<u8>`.
///
/// Prefer `write_to_file` when the destination is a filesystem path — this
/// method always materializes raw pixels and copies them into Rust memory.
/// Use [`Self::write_to_memory_owned`] to avoid that additional copy.
pub fn write_to_memory(&self) -> Result<Vec<u8>> {
Ok(self.write_to_memory_owned()?.as_slice().to_vec())
}
/// Materialize raw pixels in a libvips-owned buffer without an extra Rust
/// allocation or full-buffer copy. Drop frees the buffer with `g_free`.
pub fn write_to_memory_owned(&self) -> Result<crate::VipsOwnedBuffer> {
let mut size = 0;
// SAFETY: libvips returns a newly allocated, initialized pixel buffer.
let ptr = unsafe { vips_sys::vips_image_write_to_memory(self.as_ptr(), &mut size) };
if ptr.is_null() {
return Err(Error::Vips(
take_vips_error().unwrap_or_else(|| "could not export image pixels".into()),
));
}
// SAFETY: successful call transfers ownership of this g_free allocation.
unsafe { crate::VipsOwnedBuffer::from_raw(ptr, size) }
}
/// Encode to a Rust-owned buffer (e.g. `".jpg"`, `".png"`).
pub fn write_to_buffer(&self, suffix: &str) -> Result<Vec<u8>> {
Ok(self.write_to_buffer_owned(suffix)?.as_slice().to_vec())
}
/// Encode without copying the encoded bytes into the Rust allocator.
pub fn write_to_buffer_owned(&self, suffix: &str) -> Result<crate::VipsOwnedBuffer> {
let suffix = CString::new(suffix)
.map_err(|_| Error::Other("invalid suffix: contains NUL".into()))?;
let mut buf: *mut c_void = null_mut();
let mut size = 0;
// SAFETY: live image and valid output pointers; optional args end in NULL.
let ret = unsafe {
vips_sys::vips_image_write_to_buffer(
self.as_ptr(),
suffix.as_ptr(),
&mut buf,
&mut size,
null() as *const c_char,
)
};
// Own any returned allocation before propagating an error or empty result.
let buffer = unsafe { crate::VipsOwnedBuffer::from_raw(buf, size) }?;
ffi::ret_to_result(ret)?;
Ok(buffer)
}
/// JPEG-specific writer (quality path for `.jpg` destinations).
pub fn write_jpeg(&self, path: impl AsRef<Path>, q: Option<i32>) -> Result<()> {
let path = path_to_cstring(path.as_ref())?;
let ret = unsafe {
match q {
Some(q) => vips_sys::vips_jpegsave(
self.c.as_ptr(),
path.as_ptr(),
c"Q".as_ptr(),
q,
null() as *const c_char,
),
None => {
vips_sys::vips_jpegsave(self.c.as_ptr(), path.as_ptr(), null() as *const c_char)
}
}
};
result_draw(ret)
}
}
fn result<'a>(ptr: *mut vips_sys::VipsImage) -> Result<VipsImage<'a>> {
let owned = ffi::image_from_ptr(ptr)?;
// SAFETY: ownership transferred from libvips into this wrapper.
Ok(unsafe { VipsImage::from_raw(owned.into_ptr()) })
}
fn result_with_ret<'a>(ptr: *mut vips_sys::VipsImage, ret: c_int) -> Result<VipsImage<'a>> {
let owned = ffi::image_from_ret(ptr, ret)?;
// SAFETY: ownership transferred from libvips into this wrapper.
Ok(unsafe { VipsImage::from_raw(owned.into_ptr()) })
}
fn result_draw(ret: c_int) -> Result<()> {
ffi::ret_to_result(ret)
}
/// Loader nickname libvips would use for `path` (e.g. `"VipsForeignLoadJpegFile"`).
///
/// Returns `None` when no loader is registered for the file.
pub fn find_load(path: impl AsRef<Path>) -> Option<String> {
let path = path_to_cstring(path.as_ref()).ok()?;
// SAFETY: path is a valid C string; result is a static/owned C string.
let ptr = unsafe { vips_sys::vips_foreign_find_load(path.as_ptr()) };
if ptr.is_null() {
return None;
}
// SAFETY: non-null NUL-terminated string from libvips.
let s = unsafe { std::ffi::CStr::from_ptr(ptr) };
s.to_str().ok().map(str::to_owned)
}
/// Saver nickname libvips would use for `path` (e.g. `"VipsForeignSaveJpegFile"`).
pub fn find_save(path: impl AsRef<Path>) -> Option<String> {
let path = path_to_cstring(path.as_ref()).ok()?;
// SAFETY: path is a valid C string; result is a static/owned C string.
let ptr = unsafe { vips_sys::vips_foreign_find_save(path.as_ptr()) };
if ptr.is_null() {
return None;
}
// SAFETY: non-null NUL-terminated string from libvips.
let s = unsafe { std::ffi::CStr::from_ptr(ptr) };
s.to_str().ok().map(str::to_owned)
}
/// Create a one-band 8-bit black image (`vips_black`).
pub fn black(width: u32, height: u32) -> Result<VipsImage<'static>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: pure constructor.
let ret = unsafe {
vips_sys::vips_black(
&mut out_ptr,
width as i32,
height as i32,
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}
/// Create a two-band coordinate image (`vips_xyz`).
pub fn xyz(width: u32, height: u32) -> Result<VipsImage<'static>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: pure constructor.
let ret = unsafe {
vips_sys::vips_xyz(
&mut out_ptr,
width as i32,
height as i32,
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}
/// Create a grey ramp image (`vips_grey`).
pub fn grey(width: u32, height: u32) -> Result<VipsImage<'static>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: pure constructor.
let ret = unsafe {
vips_sys::vips_grey(
&mut out_ptr,
width as i32,
height as i32,
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}
/// Create a sine-wave test image (`vips_sines`).
pub fn sines(width: u32, height: u32) -> Result<VipsImage<'static>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: pure constructor.
let ret = unsafe {
vips_sys::vips_sines(
&mut out_ptr,
width as i32,
height as i32,
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}
/// Create a zone-plate test image (`vips_zone`).
pub fn zone(width: u32, height: u32) -> Result<VipsImage<'static>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: pure constructor.
let ret = unsafe {
vips_sys::vips_zone(
&mut out_ptr,
width as i32,
height as i32,
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}
/// Create a Perlin noise image (`vips_perlin`).
pub fn perlin(width: u32, height: u32) -> Result<VipsImage<'static>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: pure constructor.
let ret = unsafe {
vips_sys::vips_perlin(
&mut out_ptr,
width as i32,
height as i32,
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}
/// Create Gaussian noise (`vips_gaussnoise`).
pub fn gaussnoise(width: u32, height: u32) -> Result<VipsImage<'static>> {
let mut out_ptr: *mut vips_sys::VipsImage = null_mut();
// SAFETY: pure constructor.
let ret = unsafe {
vips_sys::vips_gaussnoise(
&mut out_ptr,
width as i32,
height as i32,
null() as *const c_char,
)
};
result_with_ret(out_ptr, ret)
}