pdf_oxide 0.3.59

The fastest Rust PDF library with text extraction: 0.8ms mean, 100% pass rate on 3,830 PDFs. 5× faster than pdf_extract, 17× faster than oxidize_pdf. Extract, create, and edit PDFs.
Documentation
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
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
//! Image extraction from PDF XObject resources.
//!
//! This module provides functionality to extract images from PDF documents,
//! including JPEG pass-through for DCT-encoded images and raw pixel decoding
//! for other image types.
//!
//! Phase 5

use crate::error::{Error, Result};
use crate::extractors::ccitt_bilevel;
use crate::geometry::Rect;
use crate::object::ObjectRef;
use std::cmp::min;
use std::path::Path;

/// A PDF image with metadata and pixel data.
///
/// Represents an image extracted from a PDF, including dimensions,
/// color space information, and the actual image data (either JPEG
/// or raw pixels).
#[derive(Debug, Clone, PartialEq, serde::Serialize)]
pub struct PdfImage {
    /// Image width in pixels
    width: u32,
    /// Image height in pixels
    height: u32,
    /// Color space of the image
    color_space: ColorSpace,
    /// Bits per color component (typically 8)
    bits_per_component: u8,
    /// Image data (JPEG or raw pixels)
    #[serde(skip_serializing_if = "ImageData::is_empty")]
    data: ImageData,
    /// Optional bounding box in PDF user space (v0.3.14)
    bbox: Option<Rect>,
    /// Rotation in degrees (v0.3.14)
    rotation_degrees: i32,
    /// Transformation matrix (v0.3.14)
    matrix: [f32; 6],
    /// CCITT decompression parameters (for 1-bit bilevel images)
    #[serde(skip)]
    ccitt_params: Option<crate::decoders::CcittParams>,
    /// Embedded ICC profile associated with the image's colour space,
    /// if any. For a plain `/ICCBased` image this is the profile from
    /// the array; for an `Indexed` image with an `ICCBased` base this
    /// is the base profile. `None` when the document only used
    /// device-dependent colour. Consumed by `save_as_*` to drive the
    /// CMYK→sRGB conversion through the CMM instead of the §10.3.5
    /// additive-clamp fallback.
    #[serde(skip)]
    icc_profile: Option<std::sync::Arc<crate::color::IccProfile>>,
    /// Rendering intent from the image dictionary's `/Intent`, or the
    /// graphics-state default per ISO 32000-1:2008 §8.6.5.8.
    rendering_intent: crate::color::RenderingIntent,
}

impl PdfImage {
    /// Create a new PDF image.
    pub fn new(
        width: u32,
        height: u32,
        color_space: ColorSpace,
        bits_per_component: u8,
        data: ImageData,
    ) -> Self {
        Self {
            width,
            height,
            color_space,
            bits_per_component,
            data,
            bbox: None,
            rotation_degrees: 0,
            matrix: [1.0, 0.0, 0.0, 1.0, 0.0, 0.0],
            ccitt_params: None,
            icc_profile: None,
            rendering_intent: crate::color::RenderingIntent::default(),
        }
    }

    /// Create a new PDF image with spatial metadata (v0.3.14).
    pub fn with_spatial(
        width: u32,
        height: u32,
        color_space: ColorSpace,
        bits_per_component: u8,
        data: ImageData,
        bbox: Rect,
        rotation: i32,
        matrix: [f32; 6],
    ) -> Self {
        Self {
            width,
            height,
            color_space,
            bits_per_component,
            data,
            bbox: Some(bbox),
            rotation_degrees: rotation,
            matrix,
            ccitt_params: None,
            icc_profile: None,
            rendering_intent: crate::color::RenderingIntent::default(),
        }
    }

    /// Create a new PDF image with a bounding box (v0.3.12, convenience wrapper).
    pub fn with_bbox(
        width: u32,
        height: u32,
        color_space: ColorSpace,
        bits_per_component: u8,
        data: ImageData,
        bbox: Rect,
    ) -> Self {
        Self::with_spatial(
            width,
            height,
            color_space,
            bits_per_component,
            data,
            bbox,
            0,
            [1.0, 0.0, 0.0, 1.0, 0.0, 0.0],
        )
    }

    /// Create a new PDF image with CCITT parameters.
    pub fn with_ccitt_params(
        width: u32,
        height: u32,
        color_space: ColorSpace,
        bits_per_component: u8,
        data: ImageData,
        ccitt_params: crate::decoders::CcittParams,
    ) -> Self {
        Self {
            width,
            height,
            color_space,
            bits_per_component,
            data,
            bbox: None,
            rotation_degrees: 0,
            matrix: [1.0, 0.0, 0.0, 1.0, 0.0, 0.0],
            ccitt_params: Some(ccitt_params),
            icc_profile: None,
            rendering_intent: crate::color::RenderingIntent::default(),
        }
    }

    /// Get the image width in pixels.
    pub fn width(&self) -> u32 {
        self.width
    }

    /// Get the image height in pixels.
    pub fn height(&self) -> u32 {
        self.height
    }

    /// Get the image color space.
    pub fn color_space(&self) -> &ColorSpace {
        &self.color_space
    }

    /// Get bits per component.
    pub fn bits_per_component(&self) -> u8 {
        self.bits_per_component
    }

    /// Get the image data.
    pub fn data(&self) -> &ImageData {
        &self.data
    }

    /// Get the bounding box if available.
    pub fn bbox(&self) -> Option<&Rect> {
        self.bbox.as_ref()
    }

    /// Set the bounding box for this image.
    pub fn set_bbox(&mut self, bbox: Rect) {
        self.bbox = Some(bbox);
    }

    /// Get rotation in degrees.
    pub fn rotation_degrees(&self) -> i32 {
        self.rotation_degrees
    }

    /// Set rotation in degrees.
    pub fn set_rotation_degrees(&mut self, rotation: i32) {
        self.rotation_degrees = rotation;
    }

    /// Get transformation matrix.
    pub fn matrix(&self) -> [f32; 6] {
        self.matrix
    }

    /// Set transformation matrix.
    pub fn set_matrix(&mut self, matrix: [f32; 6]) {
        self.matrix = matrix;
    }

    /// Set CCITT decompression parameters for this image.
    pub fn set_ccitt_params(&mut self, params: crate::decoders::CcittParams) {
        self.ccitt_params = Some(params);
    }

    /// Get CCITT decompression parameters if available.
    pub fn ccitt_params(&self) -> Option<&crate::decoders::CcittParams> {
        self.ccitt_params.as_ref()
    }

    /// Embedded ICC profile associated with the image, if any.
    pub fn icc_profile(&self) -> Option<&std::sync::Arc<crate::color::IccProfile>> {
        self.icc_profile.as_ref()
    }

    /// Attach an ICC profile (used by extractors; colour conversion
    /// picks it up automatically when present).
    pub fn set_icc_profile(&mut self, profile: std::sync::Arc<crate::color::IccProfile>) {
        self.icc_profile = Some(profile);
    }

    /// Rendering intent — ISO 32000-1:2008 §8.6.5.8, defaults to
    /// `RelativeColorimetric`.
    pub fn rendering_intent(&self) -> crate::color::RenderingIntent {
        self.rendering_intent
    }

    /// Set the rendering intent (used by extractors when they see an
    /// explicit `/Intent` entry on the image dictionary).
    pub fn set_rendering_intent(&mut self, intent: crate::color::RenderingIntent) {
        self.rendering_intent = intent;
    }

    /// Build the source→sRGB transform from this image's embedded ICC
    /// profile (if any). Returns `None` when the image uses purely
    /// device-dependent colour, or when no profile was resolved at
    /// extraction time.
    ///
    /// The resulting transform is component-agnostic: callers pick the
    /// matching `Transform::convert_{cmyk,rgb,gray}_*` method based on
    /// the source pixel format. Used by the `decode_cmyk_jpeg_to_rgb_…`,
    /// `cmyk_to_rgb_with_transform`, and `save_raw_as_*` paths.
    fn build_icc_transform(&self) -> Option<crate::color::Transform> {
        self.icc_profile
            .as_ref()
            .map(|p| crate::color::Transform::new_srgb_target(p.clone(), self.rendering_intent))
    }

    /// Save the image as PNG format.
    pub fn save_as_png(&self, path: impl AsRef<Path>) -> Result<()> {
        match &self.data {
            ImageData::Jpeg(jpeg_data) => {
                if self.color_space.components() == 4 {
                    let transform = self.build_icc_transform();
                    let rgb = decode_cmyk_jpeg_to_rgb_with_profile(jpeg_data, transform.as_ref())?;
                    let buf = image::ImageBuffer::<image::Rgb<u8>, _>::from_raw(
                        self.width,
                        self.height,
                        rgb,
                    )
                    .ok_or_else(|| Error::Image("Invalid CMYK image dimensions".to_string()))?;
                    buf.save_with_format(path, image::ImageFormat::Png)
                        .map_err(|e| Error::Image(format!("Failed to save PNG: {}", e)))
                } else {
                    save_jpeg_as_png(jpeg_data, path)
                }
            },
            ImageData::Raw { pixels, format } => {
                // Always build the transform if a profile is present; the
                // save helper picks the right convert_* method for the
                // pixel format. RGB/Gray ICCBased samples would otherwise
                // be written as-is, which is wrong when the profile is
                // wide-gamut (Adobe RGB, ProPhoto, …) or a calibrated
                // grayscale other than sRGB gamma.
                let transform = self.build_icc_transform();
                save_raw_as_png(pixels, self.width, self.height, *format, transform.as_ref(), path)
            },
        }
    }

    /// Save the image as JPEG format.
    pub fn save_as_jpeg(&self, path: impl AsRef<Path>) -> Result<()> {
        match &self.data {
            // Pass-through for RGB / grayscale JPEGs — viewers handle those
            // uniformly. CMYK JPEGs (4-channel ColorSpace such as DeviceCMYK
            // or ICCBased N=4) must be decoded and re-encoded as RGB because
            // most viewers either fail to open CMYK JPEGs or display them
            // with inverted or washed-out colors. `decode_cmyk_jpeg_to_rgb`
            // pulls CMYK samples via `jpeg-decoder`, inspects the APP14
            // Adobe marker to detect the inverted-channel convention
            // Photoshop / InDesign / WPS write, inverts when present, then
            // does a naive CMYK→RGB conversion (full ICC profile handling
            // is a follow-up).
            ImageData::Jpeg(jpeg_data) => {
                if self.color_space.components() == 4 {
                    let transform = self.build_icc_transform();
                    let rgb = decode_cmyk_jpeg_to_rgb_with_profile(jpeg_data, transform.as_ref())?;
                    let buf = image::ImageBuffer::<image::Rgb<u8>, _>::from_raw(
                        self.width,
                        self.height,
                        rgb,
                    )
                    .ok_or_else(|| Error::Image("Invalid CMYK image dimensions".to_string()))?;
                    buf.save_with_format(path, image::ImageFormat::Jpeg)
                        .map_err(|e| Error::Image(format!("Failed to save JPEG: {}", e)))
                } else {
                    std::fs::write(path, jpeg_data).map_err(Error::from)
                }
            },
            ImageData::Raw { pixels, format } => {
                let transform = self.build_icc_transform();
                save_raw_as_jpeg(pixels, self.width, self.height, *format, transform.as_ref(), path)
            },
        }
    }

    /// Convert image to PNG bytes in memory.
    pub fn to_png_bytes(&self) -> Result<Vec<u8>> {
        use image::codecs::png::{CompressionType, FilterType, PngEncoder};
        use image::ImageEncoder;
        use std::io::Cursor;

        let mut buffer = Cursor::new(Vec::new());
        let encoder =
            PngEncoder::new_with_quality(&mut buffer, CompressionType::Fast, FilterType::NoFilter);

        match &self.data {
            ImageData::Raw { pixels, format } => {
                let expected_gray = (self.width * self.height) as usize;
                let expected_rgb = expected_gray * 3;

                if *format == PixelFormat::Grayscale
                    && matches!(self.color_space, ColorSpace::DeviceGray | ColorSpace::CalGray)
                    && pixels.len() == expected_gray
                {
                    // image 0.25 changed `write_image` to take
                    // `ExtendedColorType` — `ColorType::*` now converts
                    // through `Into`. API-only change, same semantics.
                    encoder
                        .write_image(pixels, self.width, self.height, image::ColorType::L8.into())
                        .map_err(|e| Error::Encode(format!("Failed to encode PNG: {}", e)))?;
                } else if *format == PixelFormat::RGB && pixels.len() == expected_rgb {
                    encoder
                        .write_image(pixels, self.width, self.height, image::ColorType::Rgb8.into())
                        .map_err(|e| Error::Encode(format!("Failed to encode PNG: {}", e)))?;
                } else {
                    let dynamic_image = self.to_dynamic_image()?;
                    let rgb = dynamic_image.to_rgb8();
                    encoder
                        .write_image(
                            rgb.as_raw(),
                            self.width,
                            self.height,
                            image::ColorType::Rgb8.into(),
                        )
                        .map_err(|e| Error::Encode(format!("Failed to encode PNG: {}", e)))?;
                }
            },
            ImageData::Jpeg(_) => {
                let dynamic_image = self.to_dynamic_image()?;
                let rgb = dynamic_image.to_rgb8();
                encoder
                    .write_image(
                        rgb.as_raw(),
                        self.width,
                        self.height,
                        image::ColorType::Rgb8.into(),
                    )
                    .map_err(|e| Error::Encode(format!("Failed to encode PNG: {}", e)))?;
            },
        }

        Ok(buffer.into_inner())
    }

    /// Convert image to a base64 data URI for embedding in HTML.
    pub fn to_base64_data_uri(&self) -> Result<String> {
        use base64::{engine::general_purpose::STANDARD, Engine};

        match &self.data {
            ImageData::Jpeg(jpeg_data) => {
                let base64_str = STANDARD.encode(jpeg_data);
                Ok(format!("data:image/jpeg;base64,{}", base64_str))
            },
            ImageData::Raw { .. } => {
                let png_bytes = self.to_png_bytes()?;
                let base64_str = STANDARD.encode(&png_bytes);
                Ok(format!("data:image/png;base64,{}", base64_str))
            },
        }
    }

    /// Convert this PDF image to a `DynamicImage`.
    pub fn to_dynamic_image(&self) -> Result<image::DynamicImage> {
        match &self.data {
            ImageData::Jpeg(jpeg_data) => {
                log::debug!(
                    "Decoding JPEG data ({} bytes), starts with: {:02X?}",
                    jpeg_data.len(),
                    &jpeg_data[..min(jpeg_data.len(), 16)]
                );
                image::load_from_memory(jpeg_data)
                    .map_err(|e| Error::Decode(format!("Failed to decode JPEG: {}", e)))
            },
            ImageData::Raw { pixels, format } => {
                if self.bits_per_component == 1
                    && matches!(self.color_space, ColorSpace::DeviceGray)
                {
                    let params =
                        self.ccitt_params
                            .clone()
                            .unwrap_or_else(|| crate::decoders::CcittParams {
                                columns: self.width,
                                rows: Some(self.height),
                                ..Default::default()
                            });

                    let decompressed = ccitt_bilevel::decompress_ccitt(pixels, &params)?;
                    let grayscale =
                        ccitt_bilevel::bilevel_to_grayscale(&decompressed, self.width, self.height);

                    image::ImageBuffer::<image::Luma<u8>, Vec<u8>>::from_raw(
                        self.width,
                        self.height,
                        grayscale,
                    )
                    .ok_or_else(|| Error::Decode("Invalid image dimensions".to_string()))
                    .map(image::DynamicImage::ImageLuma8)
                } else {
                    match (format, self.color_space) {
                        (PixelFormat::RGB, ColorSpace::DeviceRGB) => {
                            image::ImageBuffer::<image::Rgb<u8>, Vec<u8>>::from_raw(
                                self.width,
                                self.height,
                                pixels.clone(),
                            )
                            .ok_or_else(|| Error::Decode("Invalid image dimensions".to_string()))
                            .map(image::DynamicImage::ImageRgb8)
                        },
                        (PixelFormat::Grayscale, ColorSpace::DeviceGray) => {
                            image::ImageBuffer::<image::Luma<u8>, Vec<u8>>::from_raw(
                                self.width,
                                self.height,
                                pixels.clone(),
                            )
                            .ok_or_else(|| Error::Decode("Invalid image dimensions".to_string()))
                            .map(image::DynamicImage::ImageLuma8)
                        },
                        _ => {
                            let rgb_pixels = match format {
                                PixelFormat::Grayscale => {
                                    pixels.iter().flat_map(|&g| vec![g, g, g]).collect()
                                },
                                PixelFormat::CMYK => cmyk_to_rgb_with_transform(
                                    pixels,
                                    self.build_icc_transform().as_ref(),
                                ),
                                PixelFormat::RGB => pixels.clone(),
                            };
                            image::ImageBuffer::<image::Rgb<u8>, Vec<u8>>::from_raw(
                                self.width,
                                self.height,
                                rgb_pixels,
                            )
                            .ok_or_else(|| Error::Decode("Invalid image dimensions".to_string()))
                            .map(image::DynamicImage::ImageRgb8)
                        },
                    }
                }
            },
        }
    }
}

/// Image data representation.
#[derive(Debug, Clone, PartialEq, serde::Serialize)]
#[serde(untagged)]
pub enum ImageData {
    /// JPEG-encoded image data.
    Jpeg(Vec<u8>),
    /// Raw pixel data with a specified format.
    Raw {
        /// Raw pixel bytes.
        pixels: Vec<u8>,
        /// Pixel format (RGB, Grayscale, CMYK).
        format: PixelFormat,
    },
}

impl ImageData {
    /// Returns true if the image data is empty.
    pub fn is_empty(&self) -> bool {
        match self {
            ImageData::Jpeg(data) => data.is_empty(),
            ImageData::Raw { pixels, .. } => pixels.is_empty(),
        }
    }
}

/// PDF color space types.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
pub enum ColorSpace {
    /// RGB color space (3 components).
    DeviceRGB,
    /// Grayscale color space (1 component).
    DeviceGray,
    /// CMYK color space (4 components).
    DeviceCMYK,
    /// Indexed (palette-based) color space.
    Indexed,
    /// Calibrated grayscale.
    CalGray,
    /// Calibrated RGB.
    CalRGB,
    /// CIE L*a*b* color space.
    Lab,
    /// ICC profile-based color space with N components.
    ICCBased(usize),
    /// Separation (spot color) space.
    Separation,
    /// DeviceN (multi-ink) color space.
    DeviceN,
    /// Pattern color space.
    Pattern,
}

impl ColorSpace {
    /// Returns the number of color components for this color space.
    pub fn components(&self) -> usize {
        match self {
            ColorSpace::DeviceGray => 1,
            ColorSpace::DeviceRGB => 3,
            ColorSpace::DeviceCMYK => 4,
            ColorSpace::Indexed => 1,
            ColorSpace::CalGray => 1,
            ColorSpace::CalRGB => 3,
            ColorSpace::Lab => 3,
            ColorSpace::ICCBased(n) => *n,
            ColorSpace::Separation => 1,
            ColorSpace::DeviceN => 4,
            ColorSpace::Pattern => 0,
        }
    }
}

/// Pixel format for raw image data.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[allow(clippy::upper_case_acronyms)]
pub enum PixelFormat {
    /// RGB format (3 bytes per pixel).
    RGB,
    /// Grayscale format (1 byte per pixel).
    Grayscale,
    /// CMYK format (4 bytes per pixel).
    CMYK,
}

impl PixelFormat {
    /// Returns the number of bytes per pixel for this format.
    pub fn bytes_per_pixel(&self) -> usize {
        match self {
            PixelFormat::Grayscale => 1,
            PixelFormat::RGB => 3,
            PixelFormat::CMYK => 4,
        }
    }
}

fn color_space_to_pixel_format(color_space: &ColorSpace) -> PixelFormat {
    match color_space {
        ColorSpace::DeviceGray => PixelFormat::Grayscale,
        ColorSpace::DeviceRGB => PixelFormat::RGB,
        ColorSpace::DeviceCMYK => PixelFormat::CMYK,
        ColorSpace::Indexed => PixelFormat::RGB,
        ColorSpace::CalGray => PixelFormat::Grayscale,
        ColorSpace::CalRGB => PixelFormat::RGB,
        ColorSpace::Lab => PixelFormat::RGB,
        ColorSpace::ICCBased(n) => match n {
            1 => PixelFormat::Grayscale,
            3 => PixelFormat::RGB,
            4 => PixelFormat::CMYK,
            _ => PixelFormat::RGB,
        },
        ColorSpace::Separation => PixelFormat::Grayscale,
        ColorSpace::DeviceN => PixelFormat::CMYK,
        ColorSpace::Pattern => PixelFormat::RGB,
    }
}

/// Parse a ColorSpace name from a PDF object.
pub fn parse_color_space(obj: &crate::object::Object) -> Result<ColorSpace> {
    use crate::object::Object;

    match obj {
        Object::Name(name) => match name.as_str() {
            "DeviceRGB" => Ok(ColorSpace::DeviceRGB),
            "DeviceGray" => Ok(ColorSpace::DeviceGray),
            "DeviceCMYK" => Ok(ColorSpace::DeviceCMYK),
            "Pattern" => Ok(ColorSpace::Pattern),
            other => Err(Error::Image(format!("Unsupported color space: {}", other))),
        },
        Object::Array(arr) if !arr.is_empty() => {
            if let Some(name) = arr[0].as_name() {
                match name {
                    "Indexed" => Ok(ColorSpace::Indexed),
                    "CalGray" => Ok(ColorSpace::CalGray),
                    "CalRGB" => Ok(ColorSpace::CalRGB),
                    "Lab" => Ok(ColorSpace::Lab),
                    "ICCBased" => {
                        let num_components = if arr.len() > 1 {
                            if let Some(stream_dict) = arr[1].as_dict() {
                                stream_dict
                                    .get("N")
                                    .and_then(|obj| match obj {
                                        Object::Integer(n) => Some(*n as usize),
                                        _ => None,
                                    })
                                    .unwrap_or(3)
                            } else {
                                3
                            }
                        } else {
                            3
                        };
                        Ok(ColorSpace::ICCBased(num_components))
                    },
                    "Separation" => Ok(ColorSpace::Separation),
                    "DeviceN" => Ok(ColorSpace::DeviceN),
                    "Pattern" => Ok(ColorSpace::Pattern),
                    other => Err(Error::Image(format!("Unsupported array color space: {}", other))),
                }
            } else {
                Err(Error::Image("Color space array must start with a name".to_string()))
            }
        },
        _ => Err(Error::Image(format!("Invalid color space object: {:?}", obj))),
    }
}

/// Extract an image from an XObject stream.
pub fn extract_image_from_xobject(
    doc: Option<&crate::document::PdfDocument>,
    xobject: &crate::object::Object,
    obj_ref: Option<ObjectRef>,
    color_space_map: Option<&std::collections::HashMap<String, crate::object::Object>>,
) -> Result<PdfImage> {
    use crate::object::Object;

    let dict = xobject
        .as_dict()
        .ok_or_else(|| Error::Image("XObject is not a stream".to_string()))?;

    let subtype = dict
        .get("Subtype")
        .and_then(|obj| obj.as_name())
        .ok_or_else(|| Error::Image("XObject missing /Subtype".to_string()))?;

    if subtype != "Image" {
        return Err(Error::Image(format!("XObject subtype is not Image: {}", subtype)));
    }

    let width = dict
        .get("Width")
        .and_then(|obj| obj.as_integer())
        .ok_or_else(|| Error::Image("Image missing /Width".to_string()))? as u32;

    let height = dict
        .get("Height")
        .and_then(|obj| obj.as_integer())
        .ok_or_else(|| Error::Image("Image missing /Height".to_string()))? as u32;

    let bits_per_component = dict
        .get("BitsPerComponent")
        .and_then(|obj| obj.as_integer())
        .unwrap_or(8) as u8;

    let color_space_obj = dict
        .get("ColorSpace")
        .ok_or_else(|| Error::Image("Image missing /ColorSpace".to_string()))?;

    let resolved_color_space = if let Some(d) = doc {
        let res = if let Some(obj_ref) = color_space_obj.as_reference() {
            d.load_object(obj_ref)?
        } else {
            color_space_obj.clone()
        };
        if let Object::Name(ref name) = res {
            if let Some(map) = color_space_map {
                map.get(name).cloned().unwrap_or(res)
            } else {
                res
            }
        } else {
            res
        }
    } else {
        color_space_obj.clone()
    };

    // For array-form color spaces (e.g. [/ICCBased <ref>], [/Indexed <base> <hi> <palette_ref>])
    // the second element is commonly an indirect reference to the ICC profile
    // stream / palette. `parse_color_space` only inspects the immediate
    // `Object::Stream` dict, so an unresolved reference silently falls back to
    // `N = 3` and a CMYK (N = 4) image is labelled as RGB. Resolve the stream
    // reference here so the component count reflects the real profile.
    let resolved_color_space =
        if let (Some(doc_mut), Object::Array(arr)) = (doc, &resolved_color_space) {
            if arr.len() > 1 {
                if let Some(second_ref) = arr[1].as_reference() {
                    if let Ok(resolved_second) = doc_mut.load_object(second_ref) {
                        let mut new_arr = arr.clone();
                        new_arr[1] = resolved_second;
                        Object::Array(new_arr)
                    } else {
                        resolved_color_space
                    }
                } else {
                    resolved_color_space
                }
            } else {
                resolved_color_space
            }
        } else {
            resolved_color_space
        };

    let color_space = parse_color_space(&resolved_color_space)?;
    // For Indexed color spaces, resolve the base color space and palette now so we
    // can expand indices to RGB after decoding the stream. Without this, raw
    // Indexed pixel data (1 byte per pixel) is mislabelled as RGB (3 bytes per
    // pixel) and ImageBuffer::from_raw rejects the wrong length. Fail fast if
    // the palette cannot be resolved so the error points at the real root cause
    // instead of the downstream "Invalid RGB image dimensions" symptom.
    let indexed_resolution: Option<IndexedResolution> = if color_space == ColorSpace::Indexed {
        let resolved = resolve_indexed_palette(doc, &resolved_color_space)?;
        if resolved.is_none() {
            return Err(Error::Image("Unable to resolve Indexed color space palette".to_string()));
        }
        resolved
    } else {
        None
    };

    // For a plain (non-Indexed) `[/ICCBased <stream>]` colour space,
    // capture the profile bytes so the CMM can convert through the
    // document's actual source characterisation instead of the
    // §10.3.5 additive-clamp fallback.
    //
    // When the image uses plain `/DeviceCMYK` with no ICC profile of
    // its own, fall back to the document's `/OutputIntents` CMYK
    // profile if one exists — the standard PDF/X assumption per
    // ISO 32000-1:2008 §14.11.5.
    let direct_icc_profile = if matches!(color_space, ColorSpace::ICCBased(_)) {
        resolve_icc_profile_from_obj(doc, &resolved_color_space)
    } else if color_space == ColorSpace::DeviceCMYK {
        doc.and_then(|d| d.output_intent_cmyk_profile())
    } else {
        None
    };

    // Per §8.6.5.8, an image dictionary may override the graphics-state
    // rendering intent via `/Intent`. Unrecognised names fall through
    // to `RelativeColorimetric`.
    let rendering_intent = dict
        .get("Intent")
        .and_then(|obj| obj.as_name())
        .map(crate::color::RenderingIntent::from_pdf_name)
        .unwrap_or_default();

    let filter_names = if let Some(filter_obj) = dict.get("Filter") {
        match filter_obj {
            Object::Name(name) => vec![name.clone()],
            Object::Array(filters) => filters
                .iter()
                .filter_map(|f| f.as_name().map(String::from))
                .collect(),
            _ => vec![],
        }
    } else {
        vec![]
    };

    let has_dct = filter_names.iter().any(|name| name == "DCTDecode");
    let is_jpeg_only = has_dct && filter_names.len() == 1;
    let is_jpeg_chain = has_dct && filter_names.len() > 1;

    let is_jbig2 = filter_names
        .iter()
        .any(|n| n.eq_ignore_ascii_case("JBIG2Decode"));

    let data = if is_jbig2 {
        decode_jbig2_image(xobject, obj_ref, dict, doc, width, height)?
    } else if is_jpeg_only || is_jpeg_chain {
        let decoded = if let (Some(d), Some(ref_id)) = (doc.as_ref(), obj_ref) {
            d.decode_stream_with_encryption(xobject, ref_id)?
        } else {
            xobject.decode_stream_data()?
        };
        ImageData::Jpeg(decoded)
    } else {
        let decoded_data = if let (Some(d), Some(ref_id)) = (doc.as_ref(), obj_ref) {
            d.decode_stream_with_encryption(xobject, ref_id)?
        } else {
            xobject.decode_stream_data()?
        };
        if let Some(ir) = indexed_resolution.as_ref() {
            // Build a Transform if the Indexed base has a profile so
            // palette entries render through the real CMM (when linked).
            let transform = ir
                .base_profile
                .clone()
                .map(|p| crate::color::Transform::new_srgb_target(p, rendering_intent));
            let expanded = expand_indexed_to_rgb_with_transform(
                &decoded_data,
                &ir.palette,
                ir.base_fmt,
                width,
                height,
                bits_per_component,
                transform.as_ref(),
            )?;
            ImageData::Raw {
                pixels: expanded,
                format: PixelFormat::RGB,
            }
        } else {
            let pixel_format = color_space_to_pixel_format(&color_space);
            ImageData::Raw {
                pixels: decoded_data,
                format: pixel_format,
            }
        }
    };

    // JBIG2 decode produces 8-bit-per-channel pixels regardless of the
    // XObject's BitsPerComponent (which is 1).  Override to 8 so that
    // to_dynamic_image() does not try to CCITT-decompress the output.
    let effective_bpc = if is_jbig2 { 8 } else { bits_per_component };
    let mut image = PdfImage::new(width, height, color_space, effective_bpc, data);

    // Attach the ICC profile if we found one — prefer the direct ICCBased
    // profile, then fall back to an Indexed base's profile so the CMM has
    // something to work with for palette-backed CMYK/Lab images too.
    if let Some(p) = direct_icc_profile {
        image.set_icc_profile(p);
    } else if let Some(ir) = indexed_resolution.as_ref() {
        if let Some(p) = ir.base_profile.clone() {
            image.set_icc_profile(p);
        }
    }
    image.set_rendering_intent(rendering_intent);

    if bits_per_component == 1 && image.color_space == ColorSpace::DeviceGray {
        if let Some(mut ccitt_params) =
            crate::object::extract_ccitt_params_with_width(dict.get("DecodeParms"), Some(width))
        {
            if ccitt_params.rows.is_none() {
                ccitt_params.rows = Some(height);
            }
            image.set_ccitt_params(ccitt_params);
        }
    }

    Ok(image)
}

/// Extract and parse an `ICCBased` colour-space's profile stream.
///
/// Accepts either a fully-resolved `[/ICCBased <Stream>]` array (the
/// stream is an `Object::Stream` directly), or a `[/ICCBased <Ref>]`
/// array where the second element is a live reference — in that case
/// `doc` must be supplied so we can dereference.
///
/// Returns `None` if:
///   - `cs_obj` isn't an ICCBased array,
///   - the profile stream can't be decoded,
///   - the profile bytes fail ICC header validation, or
///   - the declared `/N` disagrees with the profile header's
///     colourSpace signature (PDF §8.6.5.5 mandates they match).
///
/// No error is returned — callers treat "no profile" as "fall back to
/// device colour space" per §8.6.5.5's /Alternate clause.
pub(crate) fn resolve_icc_profile_from_obj(
    doc: Option<&crate::document::PdfDocument>,
    cs_obj: &crate::object::Object,
) -> Option<std::sync::Arc<crate::color::IccProfile>> {
    use crate::object::Object;

    let Object::Array(arr) = cs_obj else {
        return None;
    };
    if arr.len() < 2 || arr[0].as_name() != Some("ICCBased") {
        return None;
    }

    // Second element should be a stream (already resolved by the caller
    // in the common path) or a reference we still need to dereference.
    let profile_obj = match (&arr[1], doc) {
        (Object::Stream { .. }, _) => arr[1].clone(),
        (Object::Reference(r), Some(d)) => match d.load_object(*r) {
            Ok(obj) => obj,
            Err(_) => return None,
        },
        _ => return None,
    };

    let Object::Stream { dict, .. } = &profile_obj else {
        return None;
    };
    // `N` is mandatory per PDF 32000-1 §8.6.5.5 Table 66.
    let n = dict
        .get("N")
        .and_then(|obj| obj.as_integer())
        .filter(|n| matches!(*n, 1 | 3 | 4))? as u8;

    let bytes = profile_obj.decode_stream_data().ok()?;
    let profile = crate::color::IccProfile::parse(bytes, n)?;
    Some(std::sync::Arc::new(profile))
}

/// Outcome of resolving an `[/Indexed base hival lookup]` colour space:
/// the palette in the base's pixel format, plus the base's ICC profile
/// when the base is `ICCBased`.
pub(crate) struct IndexedResolution {
    pub base_fmt: PixelFormat,
    pub palette: Vec<u8>,
    /// `None` for device-dependent bases or bases we already folded
    /// colourimetrically (e.g. Lab, whose palette is rewritten to RGB
    /// before being returned).
    pub base_profile: Option<std::sync::Arc<crate::color::IccProfile>>,
}

/// Resolve an Indexed color space's base color space and palette lookup bytes.
///
/// PDF Indexed color spaces are `[/Indexed base hival lookup]` where `lookup`
/// is either a byte string or a stream of `(hival + 1) * N` bytes (N = number
/// of components in the base color space).
fn resolve_indexed_palette(
    doc: Option<&crate::document::PdfDocument>,
    cs_obj: &crate::object::Object,
) -> Result<Option<IndexedResolution>> {
    use crate::object::Object;

    let Object::Array(arr) = cs_obj else {
        return Ok(None);
    };
    if arr.len() < 4 {
        return Ok(None);
    }

    // Resolve the base color-space object. When it's an array like
    // [/ICCBased <stream_ref>], resolve inner references so
    // parse_color_space can read /N from the ICC stream dict.
    let base_obj = if let Some(d) = doc {
        let outer = if let Some(r) = arr[1].as_reference() {
            d.load_object(r)?
        } else {
            arr[1].clone()
        };
        if let Object::Array(mut inner) = outer {
            for item in inner.iter_mut() {
                if let Some(r) = item.as_reference() {
                    if let Ok(resolved) = d.load_object(r) {
                        *item = resolved;
                    }
                }
            }
            Object::Array(inner)
        } else {
            outer
        }
    } else {
        arr[1].clone()
    };
    let base_cs = parse_color_space(&base_obj)?;
    let base_fmt = color_space_to_pixel_format(&base_cs);
    let n = base_fmt.bytes_per_pixel();

    // When the base is `/ICCBased`, capture the profile bytes so the
    // extractor can later hand them to a CMM. Parse failures reduce to
    // `None` — the decoder then falls back to §10.3.5 CMYK→RGB math as
    // if no profile were present.
    let base_profile = if matches!(base_cs, ColorSpace::ICCBased(_)) {
        resolve_icc_profile_from_obj(doc, &base_obj)
    } else {
        None
    };

    // hival bounds the valid index range. Resolve via indirect reference if
    // needed; treat invalid / missing values as "unknown" and skip truncation.
    let hival_obj = if let Some(d) = doc {
        if let Some(r) = arr[2].as_reference() {
            d.load_object(r)?
        } else {
            arr[2].clone()
        }
    } else {
        arr[2].clone()
    };
    let hival: Option<usize> = hival_obj.as_integer().and_then(|i| {
        if (0..=255).contains(&i) {
            Some(i as usize)
        } else {
            None
        }
    });

    let lookup_obj = if let Some(d) = doc {
        if let Some(r) = arr[3].as_reference() {
            d.load_object(r)?
        } else {
            arr[3].clone()
        }
    } else {
        arr[3].clone()
    };
    let mut palette_bytes = match &lookup_obj {
        Object::String(s) => s.clone(),
        Object::Stream { .. } => lookup_obj.decode_stream_data()?,
        _ => return Ok(None),
    };
    if palette_bytes.is_empty() {
        return Ok(None);
    }

    // Truncate palette to the logical length implied by hival so that indices
    // greater than hival fall into the out-of-range branch of the expander.
    // Per PDF 32000-1:2008 §8.6.6.3 the lookup is exactly (hival + 1) * N bytes;
    // anything beyond that is stray data that must not be mapped to pixels.
    if let Some(h) = hival {
        let expected = (h + 1).saturating_mul(n);
        if expected > 0 && palette_bytes.len() > expected {
            palette_bytes.truncate(expected);
        }
    }

    // Device-independent colour-space palettes must be converted to
    // RGB before being handed to the expander, which assumes palette
    // bytes are already in the output colour space. Without this step
    // Lab triples are mis-interpreted as raw RGB and render with
    // perceptually wrong colours.
    if matches!(base_cs, ColorSpace::Lab) {
        let white = extract_lab_whitepoint(&base_obj);
        let rgb_palette = lab_palette_to_rgb(&palette_bytes, white);
        // Lab palettes are now RGB; no base ICC profile to carry through.
        return Ok(Some(IndexedResolution {
            base_fmt: PixelFormat::RGB,
            palette: rgb_palette,
            base_profile: None,
        }));
    }

    Ok(Some(IndexedResolution {
        base_fmt,
        palette: palette_bytes,
        base_profile,
    }))
}

/// Expand packed Indexed image indices into RGB bytes using the palette.
///
/// Supports 1, 2, 4, and 8 bit-per-component index streams. Rows are padded
/// to byte boundaries per the PDF spec.
///
/// Returns `Err(Error::Image)` when the requested dimensions would require
/// more than `MAX_INDEXED_OUTPUT_BYTES` to decode, or when the `usize`
/// arithmetic on `width * height * channels` / `width * bpc` overflows,
/// or when the input `raw` buffer is too short to supply every row of the
/// requested height. This is an input-amplification guard for maliciously
/// crafted PDFs that pair tiny streams with extreme Indexed image
/// dimensions — see issue #324.
#[cfg(test)]
fn expand_indexed_to_rgb(
    raw: &[u8],
    palette: &[u8],
    base_fmt: PixelFormat,
    width: u32,
    height: u32,
    bpc: u8,
) -> Result<Vec<u8>> {
    expand_indexed_to_rgb_with_transform(raw, palette, base_fmt, width, height, bpc, None)
}

/// Like [`expand_indexed_to_rgb`] but routes CMYK palette entries
/// through an ICC transform when one is supplied. Used during image
/// extraction when the base colour space is `/ICCBased` with N=4.
fn expand_indexed_to_rgb_with_transform(
    raw: &[u8],
    palette: &[u8],
    base_fmt: PixelFormat,
    width: u32,
    height: u32,
    bpc: u8,
    transform: Option<&crate::color::Transform>,
) -> Result<Vec<u8>> {
    /// Hard cap on the decoded output buffer size (256 MiB). Legitimate
    /// Indexed images in real PDFs are several orders of magnitude below
    /// this — the cap only fires on pathological / adversarial inputs
    /// where `width * height` is billions of pixels.
    const MAX_INDEXED_OUTPUT_BYTES: usize = 256 * 1024 * 1024;

    let w = width as usize;
    let h = height as usize;
    let n = base_fmt.bytes_per_pixel();

    // ISO 32000-2 §8.9.5.1 mandates bpc ∈ {1, 2, 4, 8} for Indexed color
    // spaces. Anything else (0, 3, 5, 6, 7, 9, 12, 16, …) used to be
    // accepted silently — bpc=0 was coerced to 1 and any other value fell
    // through the `read_index` `_ => 0` arm, producing a solid palette-
    // entry-0 image with no error. Reject up front so malformed input is
    // surfaced instead of decoded into nonsense pixels.
    if !matches!(bpc, 1 | 2 | 4 | 8) {
        return Err(Error::Image(format!(
            "Indexed image has invalid /BitsPerComponent {bpc} \
             (PDF spec requires 1, 2, 4, or 8)"
        )));
    }

    // Checked arithmetic for `bytes_per_row = ceil(w * bpc / 8)`.
    let bytes_per_row = w
        .checked_mul(bpc as usize)
        .map(|v| v.div_ceil(8))
        .ok_or_else(|| {
            Error::Image(format!("Indexed image row width overflow: {w} × {bpc} bpc exceeds usize"))
        })?;

    // Checked arithmetic for `w * h * 3` (output always written as RGB).
    let output_bytes = w
        .checked_mul(h)
        .and_then(|v| v.checked_mul(3))
        .ok_or_else(|| {
            Error::Image(format!("Indexed image output size overflow: {w} × {h} × 3 exceeds usize"))
        })?;

    if output_bytes > MAX_INDEXED_OUTPUT_BYTES {
        return Err(Error::Image(format!(
            "Indexed image decode would produce {output_bytes} bytes, \
             exceeds guard limit of {MAX_INDEXED_OUTPUT_BYTES} bytes \
             (width={w}, height={h})"
        )));
    }

    // The decoded index stream must cover every row of the image.
    // Truncated streams used to get silently zero-padded, which lets a
    // malicious PDF pair a 10-byte stream with a 10 000 × 10 000 image
    // and force a ~300 MiB allocation filled with default palette entry
    // 0. Reject that shape up front.
    let required_bytes = bytes_per_row.checked_mul(h).ok_or_else(|| {
        Error::Image(format!(
            "Indexed image required-input size overflow: {bytes_per_row} × {h} exceeds usize"
        ))
    })?;
    if raw.len() < required_bytes {
        return Err(Error::Image(format!(
            "Indexed image index stream truncated: {} bytes available, \
             {} required ({} bytes/row × {} rows)",
            raw.len(),
            required_bytes,
            bytes_per_row,
            h
        )));
    }

    let mut out = Vec::with_capacity(output_bytes);

    let read_index = |row: &[u8], x: usize| -> usize {
        match bpc {
            8 => row.get(x).copied().unwrap_or(0) as usize,
            4 => {
                let byte_idx = x / 2;
                let b = row.get(byte_idx).copied().unwrap_or(0);
                if x.is_multiple_of(2) {
                    (b >> 4) as usize
                } else {
                    (b & 0x0F) as usize
                }
            },
            2 => {
                let byte_idx = x / 4;
                let b = row.get(byte_idx).copied().unwrap_or(0);
                let shift = 6 - (x % 4) * 2;
                ((b >> shift) & 0x03) as usize
            },
            1 => {
                let byte_idx = x / 8;
                let b = row.get(byte_idx).copied().unwrap_or(0);
                let shift = 7 - (x % 8);
                ((b >> shift) & 0x01) as usize
            },
            // Unreachable: bpc is validated to be in {1, 2, 4, 8} above
            // before the closure is called, so this arm only exists to
            // satisfy exhaustiveness on `u8`.
            _ => unreachable!("bpc validated to {{1,2,4,8}} before read_index"),
        }
    };

    for y in 0..h {
        let row_start = y * bytes_per_row;
        let row_end = (row_start + bytes_per_row).min(raw.len());
        let row: &[u8] = if row_start < raw.len() {
            &raw[row_start..row_end]
        } else {
            &[]
        };
        for x in 0..w {
            let idx = read_index(row, x);
            let off = idx * n;
            if off + n > palette.len() {
                out.extend_from_slice(&[0, 0, 0]);
                continue;
            }
            match base_fmt {
                PixelFormat::RGB => out.extend_from_slice(&palette[off..off + 3]),
                PixelFormat::Grayscale => {
                    let g = palette[off];
                    out.push(g);
                    out.push(g);
                    out.push(g);
                },
                PixelFormat::CMYK => {
                    let c = palette[off];
                    let m = palette[off + 1];
                    let y_c = palette[off + 2];
                    let k = palette[off + 3];
                    let [r, g, b] = if let Some(t) = transform {
                        t.convert_cmyk_pixel(c, m, y_c, k)
                    } else {
                        cmyk_pixel_to_rgb(c, m, y_c, k)
                    };
                    out.push(r);
                    out.push(g);
                    out.push(b);
                },
            }
        }
    }
    Ok(out)
}

/// Convert a single CMYK pixel to RGB.
///
/// Shared conversion math used by both bulk CMYK→RGB and Indexed palette
/// expansion so the two paths cannot drift apart.
/// Convert one CMYK pixel to RGB using the PDF 32000-1:2008 §10.3.5 formula:
///
///   R = 1 − min(1, C + K)
///   G = 1 − min(1, M + K)
///   B = 1 − min(1, Y + K)
///
/// This is the spec-mandated fallback used whenever no ICC profile drives the
/// conversion. For pixels inside an `/ICCBased` colour space a real CMM
/// (qcms / lcms2) would replace this — tracked separately. Note the spec
/// formula is strictly additive-then-clamp; a multiplicative `(1-C)(1-K)`
/// variant is common in imaging stacks but does not match §10.3.5 on
/// heavily-inked samples.
pub(crate) fn cmyk_pixel_to_rgb(c: u8, m: u8, y: u8, k: u8) -> [u8; 3] {
    let c = c as f32 / 255.0;
    let m = m as f32 / 255.0;
    let y = y as f32 / 255.0;
    let k = k as f32 / 255.0;

    let r = ((1.0 - (c + k).min(1.0)) * 255.0).round() as u8;
    let g = ((1.0 - (m + k).min(1.0)) * 255.0).round() as u8;
    let b = ((1.0 - (y + k).min(1.0)) * 255.0).round() as u8;

    [r, g, b]
}

/// Extract `/WhitePoint` from a Lab colour-space PDF object.
///
/// The object is `[/Lab << /WhitePoint [Xw Yw Zw] >>]`. Returns the
/// whitepoint as `[Xw, Yw, Zw]`, falling back to D65 if absent.
fn extract_lab_whitepoint(cs_obj: &crate::object::Object) -> [f64; 3] {
    const D65: [f64; 3] = [0.9505, 1.0, 1.0890];
    let arr = match cs_obj {
        crate::object::Object::Array(a) => a,
        _ => return D65,
    };
    if arr.len() < 2 {
        return D65;
    }
    let dict = match &arr[1] {
        crate::object::Object::Dictionary(d) => d,
        _ => return D65,
    };
    let wp = match dict.get("WhitePoint") {
        Some(crate::object::Object::Array(a)) if a.len() >= 3 => a,
        _ => return D65,
    };
    let f = |obj: &crate::object::Object| -> Option<f64> {
        match obj {
            crate::object::Object::Real(v) => Some(*v),
            crate::object::Object::Integer(v) => Some(*v as f64),
            _ => None,
        }
    };
    match (f(&wp[0]), f(&wp[1]), f(&wp[2])) {
        (Some(x), Some(y), Some(z)) => [x, y, z],
        _ => D65,
    }
}

/// Convert a Lab-encoded palette to sRGB.
///
/// Each entry is 3 bytes: L* (byte 0), a* (byte 1), b* (byte 2).
/// Decoding per PDF 32000-1:2008 §8.6.5.4:
///   L* = byte_0 / 255.0 × 100.0
///   a* = byte_1 − 128.0   (default /Range [−128 127])
///   b* = byte_2 − 128.0
///
/// Then Lab → XYZ (whitepoint-relative) → sRGB with standard gamma.
pub(crate) fn lab_palette_to_rgb(palette: &[u8], white: [f64; 3]) -> Vec<u8> {
    let mut rgb = Vec::with_capacity(palette.len());
    for chunk in palette.chunks(3) {
        if chunk.len() < 3 {
            rgb.extend_from_slice(&[0, 0, 0]);
            continue;
        }
        let [r, g, b] = lab_pixel_to_rgb(chunk[0], chunk[1], chunk[2], white);
        rgb.push(r);
        rgb.push(g);
        rgb.push(b);
    }
    rgb
}

// NOTE: The XYZ→linear-sRGB matrix below assumes a D65 whitepoint. Lab CIEs
// whose `/WhitePoint` is non-D65 (D50 is common in print workflows) would
// strictly need chromatic adaptation (e.g., Bradford) from the source
// whitepoint to D65 before the sRGB matrix. We intentionally omit that for
// now — the vast majority of PDF `/Lab` spaces we encounter are D65 — but
// the caller's `white` is still used to scale `xw, yw, zw` so D65 and
// near-D65 whitepoints produce correct output. Non-D65 spaces will have a
// minor chromatic-adaptation error until this is revisited.
fn lab_pixel_to_rgb(l_byte: u8, a_byte: u8, b_byte: u8, white: [f64; 3]) -> [u8; 3] {
    let l_star = l_byte as f64 / 255.0 * 100.0;
    let a_star = a_byte as f64 - 128.0;
    let b_star = b_byte as f64 - 128.0;

    let fy = (l_star + 16.0) / 116.0;
    let fx = a_star / 500.0 + fy;
    let fz = fy - b_star / 200.0;

    let [xw, yw, zw] = white;
    let x = xw * f_inv(fx);
    let y = yw * f_inv(fy);
    let z = zw * f_inv(fz);

    // XYZ → linear sRGB (D65 matrix, IEC 61966-2-1:1999)
    let r_lin = 3.2406254773 * x - 1.5372079722 * y - 0.4986285987 * z;
    let g_lin = -0.9689307147 * x + 1.8757560609 * y + 0.0415175580 * z;
    let b_lin = 0.0557101204 * x - 0.2040210506 * y + 1.0569959423 * z;

    [srgb_gamma(r_lin), srgb_gamma(g_lin), srgb_gamma(b_lin)]
}

fn f_inv(t: f64) -> f64 {
    const DELTA: f64 = 6.0 / 29.0;
    if t > DELTA {
        t * t * t
    } else {
        3.0 * DELTA * DELTA * (t - 4.0 / 29.0)
    }
}

fn srgb_gamma(lin: f64) -> u8 {
    let v = if lin <= 0.0031308 {
        12.92 * lin
    } else {
        1.055 * lin.powf(1.0 / 2.4) - 0.055
    };
    (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8
}

/// Convert a raw CMYK byte stream (4 bytes per pixel) to straight RGB bytes
/// (3 bytes per pixel) using the naive per-pixel conversion.
///
/// This is a non-ICC conversion and does not handle Adobe-inverted JPEG CMYK;
/// for JPEG-encoded CMYK streams use `decode_adobe_cmyk_jpeg` instead.
pub fn cmyk_to_rgb(cmyk: &[u8]) -> Vec<u8> {
    cmyk_to_rgb_with_transform(cmyk, None)
}

/// Like [`cmyk_to_rgb`] but routes through an ICC transform when given,
/// and falls through to §10.3.5 otherwise. Used by save_raw_as_* when
/// the source image carries an ICC profile.
pub fn cmyk_to_rgb_with_transform(
    cmyk: &[u8],
    transform: Option<&crate::color::Transform>,
) -> Vec<u8> {
    if let Some(t) = transform {
        return t.convert_cmyk_buffer(cmyk);
    }
    let mut rgb = Vec::with_capacity((cmyk.len() / 4) * 3);
    for chunk in cmyk.chunks_exact(4) {
        let [r, g, b] = cmyk_pixel_to_rgb(chunk[0], chunk[1], chunk[2], chunk[3]);
        rgb.push(r);
        rgb.push(g);
        rgb.push(b);
    }
    rgb
}

/// Decode a CMYK-colourspace JPEG to straight RGB bytes, applying Adobe's
/// inverted-CMYK convention when the APP14 marker requests it.
///
/// Adobe-authored CMYK / YCCK JPEGs (which most real-world producers emit
/// for print-targeted PDFs) store channel values inverted: 0 means "full
/// ink" and 255 means "no ink". Naive CMYK→RGB conversion on those raw
/// bytes yields near-black output — exactly the symptom of the issue this
/// handles. Detecting the APP14 color-transform and inverting per channel
/// before applying the standard CMYK→RGB math produces bright, correct
/// images for Adobe JPEGs while still producing correct output for
/// non-Adobe CMYK JPEGs that store values directly.
///
/// This is still a naive (non-ICC) conversion — it ignores any embedded
/// ICC profile and therefore cannot produce print-accurate colour. Proper
/// ICC handling (qcms / lcms) is a follow-up; this path is purely about
/// emitting sRGB that viewers can display without mis-interpreting the
/// channel polarity.
/// Thin wrapper that falls back to the intent-less, profile-less
/// variant — kept as the public, backwards-compatible entry point.
pub fn decode_cmyk_jpeg_to_rgb(jpeg_data: &[u8]) -> Result<Vec<u8>> {
    decode_cmyk_jpeg_to_rgb_with_profile(jpeg_data, None)
}

/// Like [`decode_cmyk_jpeg_to_rgb`] but applies the given ICC transform
/// when provided, falling back to §10.3.5 otherwise. Used internally by
/// `PdfImage::save_as_*` when the source image carries an ICCBased
/// colour space (or when the document's `OutputIntents` supplied a
/// default CMYK profile).
pub fn decode_cmyk_jpeg_to_rgb_with_profile(
    jpeg_data: &[u8],
    transform: Option<&crate::color::Transform>,
) -> Result<Vec<u8>> {
    let mut decoder = jpeg_decoder::Decoder::new(std::io::Cursor::new(jpeg_data));
    let cmyk = decoder
        .decode()
        .map_err(|e| Error::Decode(format!("Failed to decode CMYK JPEG: {}", e)))?;
    let info = decoder
        .info()
        .ok_or_else(|| Error::Decode("JPEG info unavailable".to_string()))?;

    // Adobe APP14 marker contains a `color_transform` byte that tells
    // decoders how the channels are laid out. Value 0 on a 4-channel image
    // means "CMYK stored inverted" (the Photoshop convention); value 2
    // means "YCCK", which decoders convert to CMYK but the resulting values
    // are still inverted. Value 1 (YCbCr) only appears on 3-channel images.
    // When no APP14 is present we assume non-inverted CMYK, matching what
    // Poppler / pdfium do for bare CMYK JPEGs.
    let adobe_inverted = scan_adobe_inverted(jpeg_data);

    let pixel_count = (info.width as usize) * (info.height as usize);
    let expected = pixel_count * 4;
    if cmyk.len() < expected {
        return Err(Error::Decode(format!(
            "CMYK JPEG decoded {} bytes, expected {}",
            cmyk.len(),
            expected
        )));
    }

    // Normalize Adobe-inverted CMYK into straight CMYK first; the CMM
    // (or §10.3.5 fallback) always expects non-inverted input.
    let straight_cmyk: Vec<u8> = if adobe_inverted {
        let mut buf = Vec::with_capacity(pixel_count * 4);
        for chunk in cmyk.chunks_exact(4).take(pixel_count) {
            buf.extend_from_slice(&[
                255 - chunk[0],
                255 - chunk[1],
                255 - chunk[2],
                255 - chunk[3],
            ]);
        }
        buf
    } else {
        cmyk[..pixel_count * 4].to_vec()
    };

    if let Some(t) = transform {
        return Ok(t.convert_cmyk_buffer(&straight_cmyk));
    }

    // §10.3.5 additive-clamp fallback.
    let mut rgb = Vec::with_capacity(pixel_count * 3);
    for chunk in straight_cmyk.chunks_exact(4) {
        let [r, g, b] = cmyk_pixel_to_rgb(chunk[0], chunk[1], chunk[2], chunk[3]);
        rgb.push(r);
        rgb.push(g);
        rgb.push(b);
    }
    Ok(rgb)
}

/// Walk the JPEG marker stream looking for an APP14 "Adobe" segment, and
/// return true if its `color_transform` byte indicates inverted CMYK
/// (values 0 on 4-channel, or 2 = YCCK). Returns false if no APP14 marker
/// is present or if it reports a non-inverted layout.
fn scan_adobe_inverted(jpeg_data: &[u8]) -> bool {
    let mut i = 0;
    while i + 1 < jpeg_data.len() {
        if jpeg_data[i] != 0xFF {
            i += 1;
            continue;
        }
        let marker = jpeg_data[i + 1];
        i += 2;
        // Standalone markers (SOI, EOI, RSTn, TEM, fill bytes) have no length.
        if marker == 0x00 || marker == 0xFF {
            continue;
        }
        if matches!(marker, 0xD0..=0xD9) || marker == 0x01 {
            continue;
        }
        if i + 1 >= jpeg_data.len() {
            break;
        }
        let seg_len = u16::from_be_bytes([jpeg_data[i], jpeg_data[i + 1]]) as usize;
        if seg_len < 2 || i + seg_len > jpeg_data.len() {
            break;
        }
        if marker == 0xEE && seg_len >= 14 {
            let payload = &jpeg_data[i + 2..i + seg_len];
            if payload.len() >= 12 && payload.starts_with(b"Adobe") {
                let transform = payload[11];
                return transform == 0 || transform == 2;
            }
        }
        if marker == 0xDA {
            // Start of Scan — image data follows; no more APP markers.
            break;
        }
        i += seg_len;
    }
    false
}

fn save_jpeg_as_png(jpeg_data: &[u8], path: impl AsRef<Path>) -> Result<()> {
    use image::ImageFormat;
    let img = image::load_from_memory_with_format(jpeg_data, ImageFormat::Jpeg)
        .map_err(|e| Error::Image(format!("Failed to decode JPEG: {}", e)))?;
    img.save_with_format(path, ImageFormat::Png)
        .map_err(|e| Error::Image(format!("Failed to save PNG: {}", e)))
}

/// Decide whether a given ICC transform should actually be applied to a
/// buffer of the given pixel format. The transform was compiled for
/// whatever component count the profile advertised; applying it to a
/// mismatched buffer (e.g. a 4-component CMYK transform to a 3-channel
/// RGB buffer) would produce garbage. A `None` transform, or a
/// transform whose profile components disagree with `format`, is
/// suppressed so the caller falls through to identity / fallback math.
fn icc_matches_format(
    transform: Option<&crate::color::Transform>,
    format: PixelFormat,
) -> Option<&crate::color::Transform> {
    let t = transform?;
    let needed = match format {
        PixelFormat::RGB => 3,
        PixelFormat::Grayscale => 1,
        PixelFormat::CMYK => 4,
    };
    if t.source_n_components() == needed {
        Some(t)
    } else {
        None
    }
}

fn save_raw_as_png(
    pixels: &[u8],
    width: u32,
    height: u32,
    format: PixelFormat,
    transform: Option<&crate::color::Transform>,
    path: impl AsRef<Path>,
) -> Result<()> {
    use image::{ImageBuffer, ImageFormat, Luma, Rgb};

    match format {
        PixelFormat::RGB => {
            // RGB source through an ICC profile (Adobe RGB, ProPhoto, wide-
            // gamut cameras) → convert to sRGB before writing. With no
            // profile the bytes are assumed sRGB already and passed through.
            let rgb = match icc_matches_format(transform, format) {
                Some(t) => t.convert_rgb_buffer(pixels),
                None => pixels.to_vec(),
            };
            let img = ImageBuffer::<Rgb<u8>, _>::from_raw(width, height, rgb)
                .ok_or_else(|| Error::Image("Invalid RGB image dimensions".to_string()))?;
            img.save_with_format(path, ImageFormat::Png)
                .map_err(|e| Error::Image(format!("Failed to save PNG: {}", e)))
        },
        PixelFormat::Grayscale => {
            // A Gray ICC profile promotes to sRGB RGB; without one the
            // single channel is written as an L8 PNG.
            if let Some(t) = icc_matches_format(transform, format) {
                let rgb = t.convert_gray_buffer(pixels);
                let img =
                    ImageBuffer::<Rgb<u8>, _>::from_raw(width, height, rgb).ok_or_else(|| {
                        Error::Image("Invalid grayscale image dimensions".to_string())
                    })?;
                img.save_with_format(path, ImageFormat::Png)
                    .map_err(|e| Error::Image(format!("Failed to save PNG: {}", e)))
            } else {
                let img = ImageBuffer::<Luma<u8>, _>::from_raw(width, height, pixels.to_vec())
                    .ok_or_else(|| {
                        Error::Image("Invalid grayscale image dimensions".to_string())
                    })?;
                img.save_with_format(path, ImageFormat::Png)
                    .map_err(|e| Error::Image(format!("Failed to save PNG: {}", e)))
            }
        },
        PixelFormat::CMYK => {
            let rgb = cmyk_to_rgb_with_transform(pixels, icc_matches_format(transform, format));
            let img = ImageBuffer::<Rgb<u8>, _>::from_raw(width, height, rgb)
                .ok_or_else(|| Error::Image("Invalid CMYK image dimensions".to_string()))?;
            img.save_with_format(path, ImageFormat::Png)
                .map_err(|e| Error::Image(format!("Failed to save PNG: {}", e)))
        },
    }
}

fn save_raw_as_jpeg(
    pixels: &[u8],
    width: u32,
    height: u32,
    format: PixelFormat,
    transform: Option<&crate::color::Transform>,
    path: impl AsRef<Path>,
) -> Result<()> {
    use image::{ImageBuffer, ImageFormat, Luma, Rgb};

    match format {
        PixelFormat::RGB => {
            let rgb = match icc_matches_format(transform, format) {
                Some(t) => t.convert_rgb_buffer(pixels),
                None => pixels.to_vec(),
            };
            let img = ImageBuffer::<Rgb<u8>, _>::from_raw(width, height, rgb)
                .ok_or_else(|| Error::Image("Invalid RGB image dimensions".to_string()))?;
            img.save_with_format(path, ImageFormat::Jpeg)
                .map_err(|e| Error::Image(format!("Failed to save JPEG: {}", e)))
        },
        PixelFormat::Grayscale => {
            if let Some(t) = icc_matches_format(transform, format) {
                let rgb = t.convert_gray_buffer(pixels);
                let img =
                    ImageBuffer::<Rgb<u8>, _>::from_raw(width, height, rgb).ok_or_else(|| {
                        Error::Image("Invalid grayscale image dimensions".to_string())
                    })?;
                img.save_with_format(path, ImageFormat::Jpeg)
                    .map_err(|e| Error::Image(format!("Failed to save JPEG: {}", e)))
            } else {
                let img = ImageBuffer::<Luma<u8>, _>::from_raw(width, height, pixels.to_vec())
                    .ok_or_else(|| {
                        Error::Image("Invalid grayscale image dimensions".to_string())
                    })?;
                img.save_with_format(path, ImageFormat::Jpeg)
                    .map_err(|e| Error::Image(format!("Failed to save JPEG: {}", e)))
            }
        },
        PixelFormat::CMYK => {
            let rgb = cmyk_to_rgb_with_transform(pixels, icc_matches_format(transform, format));
            let img = ImageBuffer::<Rgb<u8>, _>::from_raw(width, height, rgb)
                .ok_or_else(|| Error::Image("Invalid CMYK image dimensions".to_string()))?;
            img.save_with_format(path, ImageFormat::Jpeg)
                .map_err(|e| Error::Image(format!("Failed to save JPEG: {}", e)))
        },
    }
}

/// Decode a JBIG2-compressed PDF image stream into raw grayscale pixels.
#[cfg(feature = "rendering")]
fn decode_jbig2_image(
    xobject: &crate::object::Object,
    obj_ref: Option<ObjectRef>,
    dict: &std::collections::HashMap<String, crate::object::Object>,
    doc: Option<&crate::document::PdfDocument>,
    width: u32,
    height: u32,
) -> Result<ImageData> {
    // The Jbig2Decoder in src/decoders/jbig2.rs is a pass-through: it returns
    // the raw compressed bitstream unchanged, which is exactly what hayro-jbig2
    // needs as input.
    let jbig2_bytes: Vec<u8> = if let (Some(d), Some(ref_id)) = (doc.as_ref(), obj_ref) {
        d.decode_stream_with_encryption(xobject, ref_id)?
    } else {
        xobject.decode_stream_data()?
    };

    // Load optional JBIG2Globals (shared symbol dictionaries referenced by multiple
    // embedded JBIG2 streams in the same PDF).
    let globals: Option<Vec<u8>> = (|| -> Option<Vec<u8>> {
        let dp = dict.get("DecodeParms")?.as_dict()?;
        let globals_ref = dp.get("JBIG2Globals")?.as_reference()?;
        let d = doc.as_ref()?;
        let globals_obj = d.load_object(globals_ref).ok()?;
        d.decode_stream_with_encryption(&globals_obj, globals_ref)
            .ok()
    })();

    let image = hayro_jbig2::Image::new_embedded(&jbig2_bytes, globals.as_deref())
        .map_err(|e| Error::Image(format!("JBIG2 decode error: {e}")))?;

    struct PixelCollector {
        pixels: Vec<u8>,
        row_buf: Vec<u8>,
    }

    impl hayro_jbig2::Decoder for PixelCollector {
        fn push_pixel(&mut self, black: bool) {
            self.row_buf.push(if black { 0 } else { 255 });
        }

        // chunk_count is the number of 8-pixel groups, not individual pixels.
        fn push_pixel_chunk(&mut self, black: bool, chunk_count: u32) {
            let v = if black { 0u8 } else { 255u8 };
            let n = chunk_count as usize * 8;
            self.row_buf.extend(std::iter::repeat_n(v, n));
        }

        fn next_line(&mut self) {
            self.pixels.append(&mut self.row_buf);
        }
    }

    let mut collector = PixelCollector {
        pixels: Vec::with_capacity((width * height) as usize),
        row_buf: Vec::with_capacity(width as usize),
    };

    image
        .decode(&mut collector)
        .map_err(|e| Error::Image(format!("JBIG2 pixel decode error: {e}")))?;

    Ok(ImageData::Raw {
        pixels: collector.pixels,
        format: PixelFormat::Grayscale,
    })
}

#[cfg(not(feature = "rendering"))]
fn decode_jbig2_image(
    _xobject: &crate::object::Object,
    _obj_ref: Option<ObjectRef>,
    _dict: &std::collections::HashMap<String, crate::object::Object>,
    _doc: Option<&crate::document::PdfDocument>,
    _width: u32,
    _height: u32,
) -> Result<ImageData> {
    Err(Error::UnsupportedFilter("JBIG2Decode".to_string()))
}

/// Expand abbreviated inline image dictionary keys to full names.
pub fn expand_inline_image_dict(
    dict: std::collections::HashMap<String, crate::object::Object>,
) -> std::collections::HashMap<String, crate::object::Object> {
    use std::collections::HashMap;
    let mut expanded = HashMap::new();
    for (key, value) in dict {
        let expanded_key = match key.as_str() {
            "W" => "Width",
            "H" => "Height",
            "CS" => "ColorSpace",
            "BPC" => "BitsPerComponent",
            "F" => "Filter",
            "DP" => "DecodeParms",
            "IM" => "ImageMask",
            "I" => "Interpolate",
            "D" => "Decode",
            "EF" => "EFontFile",
            "Intent" => "Intent",
            _ => &key,
        };
        expanded.insert(expanded_key.to_string(), value);
    }
    expanded
}

#[cfg(test)]
mod indexed_tests {
    use super::*;

    #[test]
    fn expand_indexed_rgb_8bpc() {
        // 2x2 image, 4 palette entries, each RGB
        let palette = vec![
            0, 0, 0, // index 0 black
            255, 0, 0, // index 1 red
            0, 255, 0, // index 2 green
            0, 0, 255, // index 3 blue
        ];
        let raw = vec![0, 1, 2, 3];
        let out = expand_indexed_to_rgb(&raw, &palette, PixelFormat::RGB, 2, 2, 8).unwrap();
        assert_eq!(out, vec![0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 255]);
    }

    #[test]
    fn expand_indexed_gray_base_to_rgb() {
        // Base color space is Grayscale, palette is 1 byte per entry
        let palette = vec![10, 128, 255];
        let raw = vec![0, 1, 2];
        let out = expand_indexed_to_rgb(&raw, &palette, PixelFormat::Grayscale, 3, 1, 8).unwrap();
        assert_eq!(out, vec![10, 10, 10, 128, 128, 128, 255, 255, 255]);
    }

    #[test]
    fn expand_indexed_out_of_range_index() {
        // Palette only has 2 entries but raw has index 5 → zeroed
        let palette = vec![10, 20, 30, 40, 50, 60];
        let raw = vec![0, 5];
        let out = expand_indexed_to_rgb(&raw, &palette, PixelFormat::RGB, 2, 1, 8).unwrap();
        assert_eq!(out, vec![10, 20, 30, 0, 0, 0]);
    }

    #[test]
    fn resolve_indexed_palette_truncates_to_hival() {
        use crate::object::Object;
        // [/Indexed /DeviceRGB 1 <inline palette>] — hival = 1, so 2 entries * 3 = 6 bytes.
        // Provide an oversized 12-byte palette; the extra 6 bytes must be dropped so
        // that indices > hival cannot pick up stray lookup data.
        let cs = Object::Array(vec![
            Object::Name("Indexed".to_string()),
            Object::Name("DeviceRGB".to_string()),
            Object::Integer(1),
            Object::String(vec![
                10, 20, 30, // entry 0
                40, 50, 60, // entry 1
                70, 80, 90, // stray — beyond hival
                100, 110, 120,
            ]),
        ]);
        let ir = resolve_indexed_palette(None, &cs).unwrap().unwrap();
        assert_eq!(ir.base_fmt, PixelFormat::RGB);
        assert_eq!(ir.palette, vec![10, 20, 30, 40, 50, 60]);
        assert!(ir.base_profile.is_none(), "DeviceRGB base has no ICC profile");
        let (fmt, palette) = (ir.base_fmt, ir.palette);

        // Index 2 (> hival) must now be treated as out-of-range → black pixel.
        let raw = vec![0, 1, 2];
        let out = expand_indexed_to_rgb(&raw, &palette, fmt, 3, 1, 8).unwrap();
        assert_eq!(out, vec![10, 20, 30, 40, 50, 60, 0, 0, 0]);
    }

    #[test]
    fn expand_indexed_cmyk_base_matches_cmyk_to_rgb() {
        // Palette has a single CMYK entry; expansion must match the shared helper.
        let palette = vec![64, 128, 192, 32];
        let raw = vec![0];
        let out = expand_indexed_to_rgb(&raw, &palette, PixelFormat::CMYK, 1, 1, 8).unwrap();
        let expected = cmyk_pixel_to_rgb(64, 128, 192, 32);
        assert_eq!(out, expected.to_vec());
    }

    #[test]
    fn expand_indexed_1bpc_with_row_padding() {
        // 2-entry palette, 5x2 image at 1 bpc. 5 bits → 1 byte per row (3 bits padding).
        // Row 0 indices: 0,1,0,1,0 → top nibble 01010xxx = 0x50
        // Row 1 indices: 1,1,0,0,1 → top nibble 11001xxx = 0xC8
        let palette = vec![10, 20, 30, 200, 210, 220];
        let raw = vec![0x50, 0xC8];
        let out = expand_indexed_to_rgb(&raw, &palette, PixelFormat::RGB, 5, 2, 1).unwrap();
        assert_eq!(
            out,
            vec![
                10, 20, 30, 200, 210, 220, 10, 20, 30, 200, 210, 220, 10, 20, 30, // row 0
                200, 210, 220, 200, 210, 220, 10, 20, 30, 10, 20, 30, 200, 210, 220, // row 1
            ]
        );
    }

    #[test]
    fn expand_indexed_2bpc_with_row_padding() {
        // 4-entry palette, 3x1 image at 2 bpc. 6 bits → 1 byte per row (2 bits padding).
        // indices 0,1,2 → 00 01 10 xx → 0x18
        let palette = vec![
            0, 0, 0, // 0
            10, 20, 30, // 1
            40, 50, 60, // 2
            70, 80, 90, // 3
        ];
        let raw = vec![0x18];
        let out = expand_indexed_to_rgb(&raw, &palette, PixelFormat::RGB, 3, 1, 2).unwrap();
        assert_eq!(out, vec![0, 0, 0, 10, 20, 30, 40, 50, 60]);
    }

    #[test]
    fn expand_indexed_4bpc_packs_two_per_byte() {
        // 4x1 image, 4bpc: 2 indices per byte, high nibble first
        let palette = vec![
            0, 0, 0, // 0
            10, 20, 30, // 1
            40, 50, 60, // 2
            70, 80, 90, // 3
        ];
        // indices: 0,1,2,3 → packed: 0x01, 0x23
        let raw = vec![0x01, 0x23];
        let out = expand_indexed_to_rgb(&raw, &palette, PixelFormat::RGB, 4, 1, 4).unwrap();
        assert_eq!(out, vec![0, 0, 0, 10, 20, 30, 40, 50, 60, 70, 80, 90]);
    }

    // ---- DoS / hardening guards for #324 ----

    #[test]
    fn expand_indexed_rejects_overflow_dimensions() {
        // Dimensions that overflow usize when computing w * h * 3. Previously
        // Vec::with_capacity(w*h*3) would panic or reserve absurd amounts.
        let palette = vec![0, 0, 0, 255, 0, 0];
        let raw = vec![0, 1];
        let huge = u32::MAX / 2;
        let result = expand_indexed_to_rgb(&raw, &palette, PixelFormat::RGB, huge, huge, 8);
        assert!(result.is_err(), "overflow dimensions must be rejected");
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("overflow") || err.contains("exceeds"),
            "expected overflow/limit error, got: {err}"
        );
    }

    #[test]
    fn expand_indexed_rejects_truncated_stream() {
        // 10x10 8bpc image requires 100 index bytes. Supplying 10 used to
        // silently zero-pad the remaining rows; now it's an error.
        let palette = vec![10, 20, 30, 40, 50, 60];
        let raw = vec![0; 10];
        let result = expand_indexed_to_rgb(&raw, &palette, PixelFormat::RGB, 10, 10, 8);
        assert!(result.is_err(), "truncated stream must be rejected");
        let err = result.unwrap_err().to_string();
        assert!(err.contains("truncated"), "expected truncated error, got: {err}");
    }

    #[test]
    fn expand_indexed_rejects_output_over_cap() {
        // 12 000 × 12 000 × 3 = 432 MB > 256 MB guard. The MAX_INDEXED_OUTPUT_BYTES
        // check fires before we inspect `raw.len()`, so the test doesn't need to
        // allocate a 144 MB stream — an empty buffer is enough to prove the cap
        // rejects the request.
        let palette = vec![0, 0, 0];
        let raw: Vec<u8> = Vec::new();
        let result = expand_indexed_to_rgb(&raw, &palette, PixelFormat::RGB, 12_000, 12_000, 8);
        assert!(result.is_err(), "oversized output must be rejected");
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("guard limit") || err.contains("exceeds"),
            "expected output-size guard error, got: {err}"
        );
    }

    // ---- #338: bpc validation per ISO 32000-2 §8.9.5.1 ----

    #[test]
    fn expand_indexed_rejects_bpc_zero() {
        // bpc = 0 used to be coerced to 1 by `bpc.max(1)`, silently
        // accepting a malformed PDF. Now it must be rejected.
        let palette = vec![0, 0, 0, 255, 0, 0];
        let raw = vec![0xFF];
        let result = expand_indexed_to_rgb(&raw, &palette, PixelFormat::RGB, 1, 1, 0);
        assert!(result.is_err(), "bpc=0 must be rejected");
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("BitsPerComponent") || err.contains("bpc"),
            "expected bpc error, got: {err}"
        );
    }

    #[test]
    fn expand_indexed_rejects_unsupported_bpc() {
        // 3, 5, 6, 7, 9, 12, 16, … are all invalid for Indexed. Previously
        // the `_ => 0` arm in `read_index` silently mapped every pixel to
        // palette entry 0, returning a solid-color image. Now they're
        // rejected up front.
        let palette = vec![0, 0, 0, 255, 0, 0];
        let raw = vec![0xFF];
        for bpc in [3u8, 5, 6, 7, 9, 12, 16] {
            let result = expand_indexed_to_rgb(&raw, &palette, PixelFormat::RGB, 1, 1, bpc);
            assert!(result.is_err(), "bpc={bpc} must be rejected");
        }
    }

    #[test]
    fn expand_indexed_accepts_all_spec_bpc_values() {
        // Sanity: 1, 2, 4, 8 must still all work.
        let palette = vec![0, 0, 0, 255, 0, 0, 10, 20, 30, 40, 50, 60];
        let raw = vec![0xFF];
        for bpc in [1u8, 2, 4, 8] {
            let result = expand_indexed_to_rgb(&raw, &palette, PixelFormat::RGB, 1, 1, bpc);
            assert!(result.is_ok(), "bpc={bpc} must be accepted, got {result:?}");
        }
    }

    // Regression test for #336. Per ISO 32000-1 §8.6.6.3, the lookup element of
    // `[/Indexed base hival lookup]` must be either a byte string or a stream.
    // Historical behaviour when it was neither: `resolve_indexed_palette` returned
    // `Ok(None)` and `extract_image_from_xobject` silently fell back to treating
    // the raw 1-byte/pixel index stream as 3-byte/pixel RGB, producing the
    // misleading "Invalid RGB image dimensions" error. The fix returns an
    // explicit `Error::Image("Unable to resolve Indexed color space palette")`.
    #[test]
    fn resolve_indexed_palette_array_lookup_returns_none() {
        use crate::object::Object;
        let cs = Object::Array(vec![
            Object::Name("Indexed".to_string()),
            Object::Name("DeviceRGB".to_string()),
            Object::Integer(1),
            // Lookup as Array-of-Array (not String or Stream) — unresolvable.
            Object::Array(vec![
                Object::Array(vec![Object::Integer(0), Object::Integer(0), Object::Integer(0)]),
                Object::Array(vec![
                    Object::Integer(255),
                    Object::Integer(255),
                    Object::Integer(255),
                ]),
            ]),
        ]);
        assert!(resolve_indexed_palette(None, &cs).unwrap().is_none());
    }

    #[test]
    fn extract_image_errors_when_indexed_lookup_is_array() {
        use crate::object::Object;
        use std::collections::HashMap;

        let mut dict = HashMap::new();
        dict.insert("Subtype".to_string(), Object::Name("Image".to_string()));
        dict.insert("Width".to_string(), Object::Integer(2));
        dict.insert("Height".to_string(), Object::Integer(1));
        dict.insert("BitsPerComponent".to_string(), Object::Integer(8));
        dict.insert(
            "ColorSpace".to_string(),
            Object::Array(vec![
                Object::Name("Indexed".to_string()),
                Object::Name("DeviceRGB".to_string()),
                Object::Integer(1),
                Object::Array(vec![Object::Integer(0), Object::Integer(0), Object::Integer(0)]),
            ]),
        );
        let xobject = Object::Stream {
            dict,
            data: bytes::Bytes::from_static(&[0, 1]),
        };

        let err = extract_image_from_xobject(None, &xobject, None, None)
            .expect_err("Indexed with Array lookup must error");
        let msg = format!("{err:?}");
        assert!(
            msg.contains("Unable to resolve Indexed color space palette"),
            "error message should identify palette-resolution failure, got: {msg}"
        );
        assert!(
            !msg.contains("Invalid RGB image dimensions"),
            "must not fall through to misleading RGB-dimension error, got: {msg}"
        );
    }

    // #337 Lab→XYZ→sRGB conversion tests

    #[test]
    fn lab_pixel_mid_gray() {
        // Lab(50, 0, 0) = perceptual mid-gray → sRGB ~(119, 119, 119).
        // Byte encoding: L=128, a=128, b=128.
        let d65: [f64; 3] = [0.9505, 1.0, 1.0890];
        let [r, g, b] = super::lab_pixel_to_rgb(128, 128, 128, d65);
        for (label, v, expected) in [("R", r, 119), ("G", g, 119), ("B", b, 119)] {
            let diff = (v as i32 - expected).abs();
            assert!(diff <= 3, "Lab(50,0,0) {label}: expected ~{expected}, got {v} (Δ={diff})");
        }
    }

    #[test]
    fn lab_pixel_white() {
        // Lab(100, 0, 0) = white → sRGB ~(255, 255, 255).
        // Byte encoding: L=255, a=128, b=128.
        let d65: [f64; 3] = [0.9505, 1.0, 1.0890];
        let [r, g, b] = super::lab_pixel_to_rgb(255, 128, 128, d65);
        for (label, v) in [("R", r), ("G", g), ("B", b)] {
            assert!(v >= 250, "Lab(100,0,0) {label}: expected ~255, got {v}");
        }
    }

    #[test]
    fn lab_pixel_black() {
        // Lab(0, 0, 0) = black → sRGB ~(0, 0, 0).
        // Byte encoding: L=0, a=128, b=128.
        let d65: [f64; 3] = [0.9505, 1.0, 1.0890];
        let [r, g, b] = super::lab_pixel_to_rgb(0, 128, 128, d65);
        for (label, v) in [("R", r), ("G", g), ("B", b)] {
            assert!(v <= 5, "Lab(0,0,0) {label}: expected ~0, got {v}");
        }
    }

    #[test]
    fn lab_pixel_red_tint() {
        // Lab(50, 80, 0) has a strong red-magenta tint.
        // Byte encoding: L=128, a=208 (128+80), b=128.
        let d65: [f64; 3] = [0.9505, 1.0, 1.0890];
        let [r, g, b] = super::lab_pixel_to_rgb(128, 208, 128, d65);
        assert!(r > g + 50, "Lab(50,80,0) should have R >> G: R={r}, G={g}");
        assert!(r > b, "Lab(50,80,0) should have R > B: R={r}, B={b}");
    }

    #[test]
    fn lab_palette_round_trip() {
        // 3-entry Lab palette → RGB palette should have 9 bytes.
        let d65: [f64; 3] = [0.9505, 1.0, 1.0890];
        let palette: Vec<u8> = vec![
            0, 128, 128, // black
            128, 128, 128, // mid-gray
            255, 128, 128, // white
        ];
        let rgb = super::lab_palette_to_rgb(&palette, d65);
        assert_eq!(rgb.len(), 9, "3 Lab entries → 9 RGB bytes");
        // Black entry: all near 0
        assert!(rgb[0] <= 5 && rgb[1] <= 5 && rgb[2] <= 5);
        // White entry: all near 255
        assert!(rgb[6] >= 250 && rgb[7] >= 250 && rgb[8] >= 250);
    }

    #[test]
    fn extract_lab_whitepoint_d65() {
        use crate::object::Object;
        let cs = Object::Array(vec![
            Object::Name("Lab".to_string()),
            Object::Dictionary({
                let mut d = std::collections::HashMap::new();
                d.insert(
                    "WhitePoint".to_string(),
                    Object::Array(vec![
                        Object::Real(0.9505),
                        Object::Real(1.0),
                        Object::Real(1.0890),
                    ]),
                );
                d
            }),
        ]);
        let wp = super::extract_lab_whitepoint(&cs);
        assert!((wp[0] - 0.9505).abs() < 1e-6);
        assert!((wp[1] - 1.0).abs() < 1e-6);
        assert!((wp[2] - 1.0890).abs() < 1e-6);
    }

    #[test]
    fn extract_lab_whitepoint_missing_falls_back_to_d65() {
        use crate::object::Object;
        let cs = Object::Name("Lab".to_string());
        let wp = super::extract_lab_whitepoint(&cs);
        assert!((wp[0] - 0.9505).abs() < 1e-6);
    }
}

// ── Phase 1 / Phase 2 split: enumerate-then-materialize image API ─────────────

/// A PDF stream filter as stored in the `/Filter` key of an image XObject.
///
/// Knowing the filter chain lets callers decide whether to decode (e.g. skip
/// decompression for JPEG re-embed pipelines that only need `raw_compressed_bytes`).
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub enum PdfFilter {
    /// JPEG (DCTDecode) — compressed bytes are a valid JPEG file.
    DCTDecode,
    /// JPEG 2000 (JPXDecode).
    JPXDecode,
    /// Deflate/zlib (FlateDecode).
    FlateDecode,
    /// LZW compression (LZWDecode).
    LZWDecode,
    /// CCITT Group 3/4 fax (CCITTFaxDecode).
    CCITTFaxDecode,
    /// JBIG2 bi-level compression.
    JBIG2Decode,
    /// ASCII hex encoding (ASCIIHexDecode).
    ASCIIHexDecode,
    /// ASCII base-85 encoding (ASCII85Decode).
    ASCII85Decode,
    /// Run-length encoding (RunLengthDecode).
    RunLengthDecode,
    /// Crypt filter (used with encrypted streams).
    Crypt,
    /// Any filter not listed above; carries the raw PDF name.
    Other(String),
}

impl PdfFilter {
    /// Map a PDF filter name (or its abbreviated form) to a `PdfFilter` variant.
    pub fn from_name(name: &str) -> Self {
        match name {
            "DCTDecode" | "DCT" => PdfFilter::DCTDecode,
            "JPXDecode" => PdfFilter::JPXDecode,
            "FlateDecode" | "Fl" => PdfFilter::FlateDecode,
            "LZWDecode" | "LZW" => PdfFilter::LZWDecode,
            "CCITTFaxDecode" | "CCF" => PdfFilter::CCITTFaxDecode,
            "JBIG2Decode" => PdfFilter::JBIG2Decode,
            "ASCIIHexDecode" | "AHx" => PdfFilter::ASCIIHexDecode,
            "ASCII85Decode" | "A85" => PdfFilter::ASCII85Decode,
            "RunLengthDecode" | "RL" => PdfFilter::RunLengthDecode,
            "Crypt" => PdfFilter::Crypt,
            other => PdfFilter::Other(other.to_string()),
        }
    }
}

/// Parses the `/Filter` entry of an image dictionary into a `Vec<PdfFilter>`.
///
/// The spec allows either a single name (`/DCTDecode`) or an array of names
/// (`[/ASCII85Decode /FlateDecode]`).
pub(crate) fn parse_filter_chain(
    dict: &std::collections::HashMap<String, crate::object::Object>,
) -> Vec<PdfFilter> {
    use crate::object::Object;
    match dict.get("Filter") {
        Some(Object::Name(n)) => vec![PdfFilter::from_name(n)],
        Some(Object::Array(arr)) => arr
            .iter()
            .filter_map(|o| o.as_name())
            .map(PdfFilter::from_name)
            .collect(),
        _ => vec![],
    }
}

/// Internal image source stored inside a [`PdfImageHandle`].
#[derive(Clone)]
enum PdfImageSource {
    /// Indirect Image XObject reference; loaded on demand.
    XObject(ObjectRef),
    /// Inline image: pre-built `Object::Stream` plus the raw compressed bytes.
    Inline {
        /// Synthetic `Object::Stream` built from the inline dict + data —
        /// ready to pass directly to `extract_image_from_xobject`.
        stream_object: crate::object::Object,
        /// Raw compressed bytes as they appeared between `ID` and `EI`.
        /// Stored as `bytes::Bytes` (cheaply cloneable, refcounted) so that
        /// the same allocation can be shared with the Stream data field
        /// without duplicating a potentially large JPEG/JBIG2/etc payload.
        compressed_bytes: bytes::Bytes,
    },
}

/// A lightweight handle to a PDF image that has **not** been decoded yet.
///
/// Created by [`crate::PdfDocument::page_image_handles`], which walks the page content
/// stream and reads XObject dictionary metadata without decompressing any stream.
/// Callers can inspect the metadata fields to decide which images to materialise,
/// then call [`decode`](PdfImageHandle::decode) or
/// [`raw_compressed_bytes`](PdfImageHandle::raw_compressed_bytes) only on those
/// they actually need.
///
/// # Example
///
/// ```no_run
/// # use pdf_oxide::PdfDocument;
/// # let bytes = std::fs::read("page.pdf").unwrap();
/// let doc = PdfDocument::from_bytes(bytes).unwrap();
/// // Phase 1: enumerate without decompression
/// let handles = doc.page_image_handles(0).unwrap();
/// // Phase 2: decode only images larger than a thumbnail
/// let images: Vec<_> = handles
///     .into_iter()
///     .filter(|h| h.width >= 200 && h.height >= 200)
///     .map(|h| h.decode())
///     .collect::<Result<_, _>>()
///     .unwrap();
/// ```
#[derive(Clone)]
#[non_exhaustive]
pub struct PdfImageHandle<'doc> {
    /// Image width in pixels (from XObject `/Width`).
    pub width: u32,
    /// Image height in pixels (from XObject `/Height`).
    pub height: u32,
    /// Colour space (from XObject `/ColorSpace`).
    pub color_space: ColorSpace,
    /// Bits per component (from XObject `/BitsPerComponent`).
    pub bits_per_component: u8,
    /// Compressed stream length in bytes (from XObject `/Length`).
    ///
    /// For inline images this is `data.len()` as stored between `ID` and `EI`.
    pub byte_size_compressed: u64,
    /// Ordered list of filters applied to the stream (outermost first).
    pub filter_chain: Vec<PdfFilter>,
    /// `true` if the image is an inline image (embedded in the content stream).
    pub is_inline: bool,
    /// Zero-based index of this image among all images painted on the page,
    /// in content-stream paint order.
    pub paint_order: usize,
    /// Axis-aligned bounding box of this image in PDF user space, computed
    /// during Phase 1 by applying the current transformation matrix to the
    /// unit rectangle `[0,0,1,1]`.
    pub bbox: crate::geometry::Rect,
    /// Rotation angle in degrees (0, 90, 180, or 270), derived from the CTM
    /// during Phase 1.
    pub rotation_degrees: f32,

    // Internal fields
    ctm: crate::content::Matrix,
    doc: &'doc crate::document::PdfDocument,
    source: PdfImageSource,
    /// Active resource `/ColorSpace` subdictionary (name → resolved Object) for
    /// this image's scope, so `decode()` can resolve a resource-name
    /// `/ColorSpace` (e.g. `/CS0`) the same way the renderer does. Empty when the
    /// image's colour space needs no resource lookup (the common case), which
    /// preserves the original `color_space_map=None` decode path.
    color_space_resources: std::collections::HashMap<String, crate::object::Object>,
    /// For an Indexed image (`[/Indexed base hival lookup]`, §8.6.6.3), the
    /// resolved de-indexed *base* colour space; `None` for non-Indexed images.
    indexed_base: Option<ColorSpace>,
}

impl<'doc> PdfImageHandle<'doc> {
    /// Decode this image into a [`PdfImage`].
    ///
    /// This is the expensive operation: it decompresses the image stream,
    /// decodes pixels, and applies colour-space conversions as needed.
    ///
    /// Takes `&self` so a single handle supports a two-phase inspect → raw →
    /// decode flow ([`raw_compressed_bytes`](Self::raw_compressed_bytes) then
    /// `decode`) without re-enumerating the page.
    pub fn decode(&self) -> Result<PdfImage> {
        use crate::extractors::extract_image_from_xobject;

        let xobject_for_extract;
        let (obj, obj_ref) = match &self.source {
            PdfImageSource::XObject(obj_ref) => {
                xobject_for_extract = self.doc.load_object(*obj_ref)?;
                (&xobject_for_extract, Some(*obj_ref))
            },
            PdfImageSource::Inline { stream_object, .. } => (stream_object, None),
        };

        // Pass the active resource ColorSpace map so a resource-name
        // `/ColorSpace` (e.g. `/CS0`) resolves the same way the renderer does.
        // `None` when empty preserves the original decode path for the common
        // case where the image's colour space needs no resource lookup.
        let cs_map = if self.color_space_resources.is_empty() {
            None
        } else {
            Some(&self.color_space_resources)
        };
        let mut image = extract_image_from_xobject(Some(self.doc), obj, obj_ref, cs_map)?;

        // Use pre-computed bbox and rotation from Phase 1 — no need to call
        // back into document.rs helpers here.
        image.set_bbox(self.bbox);
        image.set_matrix([
            self.ctm.a, self.ctm.b, self.ctm.c, self.ctm.d, self.ctm.e, self.ctm.f,
        ]);
        image.set_rotation_degrees(self.rotation_degrees as i32);

        Ok(image)
    }

    /// Return the raw compressed bytes exactly as stored in the PDF stream,
    /// **without** decompressing them.
    ///
    /// For JPEG images (`filter_chain == [DCTDecode]`) these bytes form a valid
    /// JPEG file and can be written directly to disk or forwarded to a downstream
    /// pipeline without recompression.
    ///
    /// Takes `&self` so it can be combined with [`decode`](Self::decode) on the
    /// same handle (inspect → raw → decode) without re-enumerating the page.
    pub fn raw_compressed_bytes(&self) -> Result<Vec<u8>> {
        match &self.source {
            PdfImageSource::XObject(obj_ref) => {
                let obj = self.doc.load_object(*obj_ref)?;
                match obj {
                    crate::object::Object::Stream { data, .. } => Ok(data.to_vec()),
                    _ => Err(crate::error::Error::Image("XObject is not a stream".to_string())),
                }
            },
            PdfImageSource::Inline {
                compressed_bytes, ..
            } => Ok(compressed_bytes.to_vec()),
        }
    }

    /// For an Indexed image, the de-indexed *base* colour space.
    ///
    /// When [`color_space`](Self::color_space) is [`ColorSpace::Indexed`] the
    /// image samples are single palette indices (`components() == 1`) into an
    /// `[/Indexed base hival lookup]` array (§8.6.6.3); this returns the resolved
    /// `base` colour space — the space in which the de-indexed output pixels are
    /// expressed. Returns `None` for every non-Indexed image (and only if an
    /// Indexed `base` could not be parsed at all).
    pub fn indexed_base(&self) -> Option<ColorSpace> {
        self.indexed_base
    }
}

impl std::fmt::Debug for PdfImageHandle<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PdfImageHandle")
            .field("width", &self.width)
            .field("height", &self.height)
            .field("color_space", &self.color_space)
            .field("bits_per_component", &self.bits_per_component)
            .field("byte_size_compressed", &self.byte_size_compressed)
            .field("filter_chain", &self.filter_chain)
            .field("is_inline", &self.is_inline)
            .field("paint_order", &self.paint_order)
            .field("bbox", &self.bbox)
            .field("rotation_degrees", &self.rotation_degrees)
            .field("color_space_resources", &self.color_space_resources)
            .field("indexed_base", &self.indexed_base)
            .finish_non_exhaustive()
    }
}

/// Derive a rotation angle in degrees from a transformation matrix.
///
/// Computes `atan2(b, a)` and rounds to the nearest integer degree.
fn matrix_to_rotation(m: crate::content::Matrix) -> f32 {
    let angle_rad = m.b.atan2(m.a);
    let angle_deg = angle_rad.to_degrees();
    let normalized = angle_deg % 360.0;
    if normalized < 0.0 {
        normalized + 360.0
    } else {
        normalized
    }
}

/// Transform an axis-aligned bounding rectangle by a CTM.
///
/// Transforms all four corners and returns the axis-aligned bounding box of the
/// result, which correctly handles rotation, shear, and negative scaling.
fn transform_bbox_with_ctm(
    rect: &crate::geometry::Rect,
    ctm: crate::content::Matrix,
) -> crate::geometry::Rect {
    let x0 = rect.x;
    let y0 = rect.y;
    let x1 = rect.x + rect.width;
    let y1 = rect.y + rect.height;

    let tx0 = ctm.a * x0 + ctm.c * y0 + ctm.e;
    let ty0 = ctm.b * x0 + ctm.d * y0 + ctm.f;

    let tx1 = ctm.a * x1 + ctm.c * y0 + ctm.e;
    let ty1 = ctm.b * x1 + ctm.d * y0 + ctm.f;

    let tx2 = ctm.a * x0 + ctm.c * y1 + ctm.e;
    let ty2 = ctm.b * x0 + ctm.d * y1 + ctm.f;

    let tx3 = ctm.a * x1 + ctm.c * y1 + ctm.e;
    let ty3 = ctm.b * x1 + ctm.d * y1 + ctm.f;

    let min_x = tx0.min(tx1).min(tx2).min(tx3);
    let max_x = tx0.max(tx1).max(tx2).max(tx3);
    let min_y = ty0.min(ty1).min(ty2).min(ty3);
    let max_y = ty0.max(ty1).max(ty2).max(ty3);

    crate::geometry::Rect {
        x: min_x,
        y: min_y,
        width: max_x - min_x,
        height: max_y - min_y,
    }
}

/// Resolve a handle's reported colour space from a raw `/ColorSpace` entry.
///
/// Shared by the XObject and inline handle builders so the two paths cannot
/// drift. Returns the `(color_space, indexed_base)` pair stored on the handle:
///
/// - **Resource-name resolution.** If `entry` is an `Object::Name` that is *not*
///   one of the standard device spaces (`DeviceGray`/`DeviceRGB`/`DeviceCMYK`/
///   `Pattern`, which "always identify the corresponding colour spaces directly"
///   and "never refer to resources", §8.6.3/§8.9.7), it is looked up in
///   `color_space_resources` (the active `/Resources/ColorSpace` subdictionary),
///   mirroring the renderer / `extract_image_from_xobject`.
/// - **Indirect-ref hop.** If the entry (or looked-up value) is a `Reference`,
///   one `load_object` hop is resolved via `doc`.
/// - **Indexed (§8.6.6.3).** When the resolved object is an
///   `[/Indexed base hival lookup]` array, returns `(ColorSpace::Indexed,
///   Some(base))` with the de-indexed `base` resolved (including an indirect
///   `base` ref and inner refs, e.g. `[/ICCBased <stream_ref>]`), reusing the
///   same base-resolution logic as `resolve_indexed_palette`. If the base cannot
///   be parsed, returns `(ColorSpace::Indexed, None)`.
/// - Otherwise returns `(parse_color_space(resolved)?, None)`, falling back to
///   `DeviceRGB` on parse failure.
fn resolve_color_space_for_handle(
    entry: &crate::object::Object,
    color_space_resources: &std::collections::HashMap<String, crate::object::Object>,
    doc: Option<&crate::document::PdfDocument>,
) -> (ColorSpace, Option<ColorSpace>) {
    use crate::object::Object;

    // (a) Resource-name → resolved Object (skip standard device names, which
    // always identify their space directly and never refer to resources).
    let after_name = match entry {
        Object::Name(name)
            if !matches!(name.as_str(), "DeviceGray" | "DeviceRGB" | "DeviceCMYK" | "Pattern") =>
        {
            color_space_resources
                .get(name)
                .cloned()
                .unwrap_or_else(|| entry.clone())
        },
        _ => entry.clone(),
    };

    // (b) Resolve one indirect-ref hop.
    let resolved = match (after_name.as_reference(), doc) {
        (Some(r), Some(d)) => d.load_object(r).unwrap_or(after_name),
        _ => after_name,
    };

    // (c) `[/Indexed base hival lookup]` (§8.6.6.3): report Indexed + base.
    if let Object::Array(arr) = &resolved {
        if arr.first().and_then(|o| o.as_name()) == Some("Indexed") && arr.len() >= 2 {
            // Resolve the base object, mirroring resolve_indexed_palette: an
            // indirect base ref, plus inner refs of an array base such as
            // [/ICCBased <stream_ref>] so parse_color_space can read /N.
            let base_obj = if let Some(d) = doc {
                let outer = if let Some(r) = arr[1].as_reference() {
                    d.load_object(r).unwrap_or_else(|_| arr[1].clone())
                } else {
                    arr[1].clone()
                };
                if let Object::Array(mut inner) = outer {
                    for item in inner.iter_mut() {
                        if let Some(r) = item.as_reference() {
                            if let Ok(resolved) = d.load_object(r) {
                                *item = resolved;
                            }
                        }
                    }
                    Object::Array(inner)
                } else {
                    outer
                }
            } else {
                arr[1].clone()
            };
            let base = parse_color_space(&base_obj).ok();
            return (ColorSpace::Indexed, base);
        }
    }

    // (d) Non-Indexed: parse directly, fall back to DeviceRGB.
    match parse_color_space(&resolved) {
        Ok(cs) => (cs, None),
        Err(_) => (ColorSpace::DeviceRGB, None),
    }
}

/// Build a `PdfImageHandle` from an Image XObject dictionary entry.
///
/// Returns `None` if the XObject reference cannot be resolved or the dict lacks
/// required fields (`Width`, `Height`), or if those fields contain non-positive
/// values.
pub(crate) fn image_handle_from_xobject<'doc>(
    doc: &'doc crate::document::PdfDocument,
    obj_ref: ObjectRef,
    xobject_dict: &std::collections::HashMap<String, crate::object::Object>,
    ctm: crate::content::Matrix,
    paint_order: usize,
    color_space_resources: &std::collections::HashMap<String, crate::object::Object>,
) -> Option<PdfImageHandle<'doc>> {
    let w = xobject_dict
        .get("Width")
        .and_then(|o| o.as_integer())
        .filter(|&n| n > 0)
        .map(|n| n as u32)?;
    let h = xobject_dict
        .get("Height")
        .and_then(|o| o.as_integer())
        .filter(|&n| n > 0)
        .map(|n| n as u32)?;
    let bpc = xobject_dict
        .get("BitsPerComponent")
        .and_then(|o| o.as_integer())
        .unwrap_or(8) as u8;
    let byte_size = xobject_dict
        .get("Length")
        .and_then(|o| o.as_integer())
        .filter(|&n| n >= 0)
        .map(|n| n as u64)
        .unwrap_or(0);
    let filter_chain = parse_filter_chain(xobject_dict);

    // Resolve the reported colour space via the shared helper: resource-name →
    // map entry, one indirect-ref hop, and `[/Indexed base ...]` (§8.6.6.3) →
    // `Indexed` + de-indexed base. Default to DeviceRGB when `/ColorSpace` is
    // absent.
    let (color_space, indexed_base) = match xobject_dict.get("ColorSpace") {
        Some(entry) => resolve_color_space_for_handle(entry, color_space_resources, Some(doc)),
        None => (ColorSpace::DeviceRGB, None),
    };

    // Compute bbox and rotation in Phase 1 while the CTM is in scope.
    let unit_rect = crate::geometry::Rect::new(0.0, 0.0, 1.0, 1.0);
    let bbox = transform_bbox_with_ctm(&unit_rect, ctm);
    let rotation_degrees = matrix_to_rotation(ctm);

    Some(PdfImageHandle {
        width: w,
        height: h,
        color_space,
        bits_per_component: bpc,
        byte_size_compressed: byte_size,
        filter_chain,
        is_inline: false,
        paint_order,
        bbox,
        rotation_degrees,
        ctm,
        doc,
        source: PdfImageSource::XObject(obj_ref),
        color_space_resources: color_space_resources.clone(),
        indexed_base,
    })
}

/// Build a `PdfImageHandle` from an inline image (`BI`/`ID`/`EI` sequence).
pub(crate) fn image_handle_from_inline<'doc>(
    doc: &'doc crate::document::PdfDocument,
    dict: &std::collections::HashMap<String, crate::object::Object>,
    data: Vec<u8>,
    ctm: crate::content::Matrix,
    paint_order: usize,
    color_space_resources: &std::collections::HashMap<String, crate::object::Object>,
) -> Option<PdfImageHandle<'doc>> {
    use crate::object::Object;

    // Inline image dicts use abbreviated keys; expand them.
    let expanded = crate::extractors::expand_inline_image_dict(dict.clone());

    let w = expanded
        .get("Width")
        .and_then(|o| o.as_integer())
        .filter(|&n| n > 0)
        .map(|n| n as u32)?;
    let h = expanded
        .get("Height")
        .and_then(|o| o.as_integer())
        .filter(|&n| n > 0)
        .map(|n| n as u32)?;
    let bpc = expanded
        .get("BitsPerComponent")
        .and_then(|o| o.as_integer())
        .unwrap_or(8) as u8;
    let byte_size = data.len() as u64;
    let filter_chain = parse_filter_chain(&expanded);

    // Resolve the reported colour space via the same shared helper as the
    // XObject path so the two agree. For inline images a resource-name
    // `/ColorSpace` into `/Resources/ColorSpace` is explicitly legal (§8.9.7),
    // and `[/Indexed base ...]` (§8.6.6.3) reports `Indexed` + de-indexed base.
    let (color_space, indexed_base) = match expanded.get("ColorSpace") {
        Some(entry) => resolve_color_space_for_handle(entry, color_space_resources, Some(doc)),
        None => (ColorSpace::DeviceRGB, None),
    };

    // Compute bbox and rotation in Phase 1 while the CTM is in scope.
    let unit_rect = crate::geometry::Rect::new(0.0, 0.0, 1.0, 1.0);
    let bbox = transform_bbox_with_ctm(&unit_rect, ctm);
    let rotation_degrees = matrix_to_rotation(ctm);

    // Build a synthetic Object::Stream so decode() can call extract_image_from_xobject.
    // Share a single Bytes allocation between the Stream (for decode) and the
    // handle (for raw_compressed_bytes). Bytes is refcounted, so this avoids
    // duplicating potentially large image payloads (e.g. 10 MB JPEG → 20 MB RSS).
    let mut stream_dict = expanded;
    stream_dict.insert("Subtype".to_string(), Object::Name("Image".to_string()));
    let compressed_bytes = bytes::Bytes::from(data);
    let stream_object = Object::Stream {
        dict: stream_dict,
        data: compressed_bytes.clone(),
    };

    Some(PdfImageHandle {
        width: w,
        height: h,
        color_space,
        bits_per_component: bpc,
        byte_size_compressed: byte_size,
        filter_chain,
        is_inline: true,
        paint_order,
        bbox,
        rotation_degrees,
        ctm,
        doc,
        source: PdfImageSource::Inline {
            stream_object,
            compressed_bytes,
        },
        color_space_resources: color_space_resources.clone(),
        indexed_base,
    })
}

#[cfg(test)]
mod handle_color_space_tests {
    use super::*;
    use crate::object::{Object, ObjectRef};
    use std::collections::HashMap;

    fn empty_map() -> HashMap<String, Object> {
        HashMap::new()
    }

    /// `[/Indexed /DeviceRGB 1 <00 00 00 FF FF FF>]` as a direct array.
    fn direct_indexed_rgb() -> Object {
        Object::Array(vec![
            Object::Name("Indexed".to_string()),
            Object::Name("DeviceRGB".to_string()),
            Object::Integer(1),
            Object::String(vec![0, 0, 0, 255, 255, 255]),
        ])
    }

    #[test]
    fn helper_direct_indexed_reports_indexed_with_rgb_base() {
        let entry = direct_indexed_rgb();
        let (cs, base) = resolve_color_space_for_handle(&entry, &empty_map(), None);
        assert_eq!(cs, ColorSpace::Indexed);
        assert_eq!(base, Some(ColorSpace::DeviceRGB));
    }

    #[test]
    fn helper_resource_name_resolves_to_device_gray() {
        // `/CS0` → /DeviceGray via the resource map (not a standard device name,
        // so it is looked up).
        let mut map = empty_map();
        map.insert("CS0".to_string(), Object::Name("DeviceGray".to_string()));
        let entry = Object::Name("CS0".to_string());
        let (cs, base) = resolve_color_space_for_handle(&entry, &map, None);
        assert_eq!(cs, ColorSpace::DeviceGray);
        assert_eq!(base, None);
    }

    #[test]
    fn helper_resource_name_resolves_to_indexed() {
        // `/CS0` → an Indexed array via the resource map: Indexed + base.
        let mut map = empty_map();
        map.insert("CS0".to_string(), direct_indexed_rgb());
        let entry = Object::Name("CS0".to_string());
        let (cs, base) = resolve_color_space_for_handle(&entry, &map, None);
        assert_eq!(cs, ColorSpace::Indexed);
        assert_eq!(base, Some(ColorSpace::DeviceRGB));
    }

    #[test]
    fn helper_standard_device_name_not_resource_resolved() {
        // A standard device name must resolve directly and never be looked up,
        // even if the map (incorrectly) shadows it.
        let mut map = empty_map();
        map.insert("DeviceRGB".to_string(), Object::Name("DeviceGray".to_string()));
        let entry = Object::Name("DeviceRGB".to_string());
        let (cs, base) = resolve_color_space_for_handle(&entry, &map, None);
        assert_eq!(cs, ColorSpace::DeviceRGB);
        assert_eq!(base, None);
    }

    /// Build a PDF whose object `99 0 obj` is the given colour-space object, so
    /// `resolve_color_space_for_handle(99 0 R, .., Some(doc))` can resolve the
    /// indirect-ref hop. The catalog/pages are minimal placeholders.
    fn pdf_with_cs_object(cs_body: &str) -> Vec<u8> {
        let mut pdf = b"%PDF-1.4\n".to_vec();
        let mut offsets: Vec<(u32, usize)> = Vec::new();

        offsets.push((1, pdf.len()));
        pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");

        offsets.push((2, pdf.len()));
        pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n");

        offsets.push((3, pdf.len()));
        pdf.extend_from_slice(
            b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 1 1] >>\nendobj\n",
        );

        offsets.push((99, pdf.len()));
        pdf.extend_from_slice(format!("99 0 obj\n{}\nendobj\n", cs_body).as_bytes());

        let xref_off = pdf.len();
        // Emit a single contiguous xref subsection covering 0..=99 with most
        // entries free; only the objects we wrote are marked in-use.
        let max_id = 99u32;
        pdf.extend_from_slice(format!("xref\n0 {}\n", max_id + 1).as_bytes());
        pdf.extend_from_slice(b"0000000000 65535 f \n");
        for id in 1..=max_id {
            if let Some((_, off)) = offsets.iter().find(|(oid, _)| *oid == id) {
                pdf.extend_from_slice(format!("{:010} 00000 n \n", off).as_bytes());
            } else {
                pdf.extend_from_slice(b"0000000000 65535 f \n");
            }
        }
        pdf.extend_from_slice(
            format!(
                "trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{}\n%%EOF\n",
                max_id + 1,
                xref_off
            )
            .as_bytes(),
        );
        pdf
    }

    #[test]
    fn helper_indirect_indexed_array_de_indexed() {
        // `/ColorSpace 99 0 R` where 99 0 obj is `[/Indexed /DeviceRGB 1 <...>]`.
        let doc = crate::document::PdfDocument::from_bytes(pdf_with_cs_object(
            "[/Indexed /DeviceRGB 1 <000000FFFFFF>]",
        ))
        .expect("synthetic pdf parses");
        let entry = Object::Reference(ObjectRef::new(99, 0));
        let (cs, base) = resolve_color_space_for_handle(&entry, &empty_map(), Some(&doc));
        assert_eq!(cs, ColorSpace::Indexed);
        assert_eq!(base, Some(ColorSpace::DeviceRGB));
    }

    #[test]
    fn helper_indirect_plain_device_gray() {
        // `/ColorSpace 99 0 R` where 99 0 obj is `/DeviceGray`.
        let doc =
            crate::document::PdfDocument::from_bytes(pdf_with_cs_object("/DeviceGray")).unwrap();
        let entry = Object::Reference(ObjectRef::new(99, 0));
        let (cs, base) = resolve_color_space_for_handle(&entry, &empty_map(), Some(&doc));
        assert_eq!(cs, ColorSpace::DeviceGray);
        assert_eq!(base, None);
    }

    #[test]
    fn inline_indexed_consistent_with_xobject() {
        // The inline path uses the same helper, so a direct Indexed array must
        // report `Indexed` + DeviceRGB base — identical to the XObject contract.
        let entry = direct_indexed_rgb();
        let (xobj_cs, xobj_base) = resolve_color_space_for_handle(&entry, &empty_map(), None);
        // Inline path: same helper, same inputs.
        let (inline_cs, inline_base) = resolve_color_space_for_handle(&entry, &empty_map(), None);
        assert_eq!(xobj_cs, inline_cs);
        assert_eq!(xobj_base, inline_base);
        assert_eq!(inline_cs, ColorSpace::Indexed);
        assert_eq!(inline_base, Some(ColorSpace::DeviceRGB));
    }

    /// Build a PDF with an image XObject (object 99) so a handle can be built
    /// against a real document and `decode()` exercised. The image is a 1×1
    /// uncompressed sample; `cs_name` is written verbatim as its `/ColorSpace`.
    fn pdf_with_image_xobject(cs_name: &str, sample: &[u8]) -> Vec<u8> {
        let mut pdf = b"%PDF-1.4\n".to_vec();
        let mut offsets: Vec<(u32, usize)> = Vec::new();

        offsets.push((1, pdf.len()));
        pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
        offsets.push((2, pdf.len()));
        pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n");
        offsets.push((3, pdf.len()));
        pdf.extend_from_slice(
            b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 1 1] >>\nendobj\n",
        );

        offsets.push((99, pdf.len()));
        let header = format!(
            "99 0 obj\n<< /Type /XObject /Subtype /Image /Width 1 /Height 1 \
             /BitsPerComponent 8 /ColorSpace {} /Length {} >>\nstream\n",
            cs_name,
            sample.len()
        );
        pdf.extend_from_slice(header.as_bytes());
        pdf.extend_from_slice(sample);
        pdf.extend_from_slice(b"\nendstream\nendobj\n");

        let xref_off = pdf.len();
        let max_id = 99u32;
        pdf.extend_from_slice(format!("xref\n0 {}\n", max_id + 1).as_bytes());
        pdf.extend_from_slice(b"0000000000 65535 f \n");
        for id in 1..=max_id {
            if let Some((_, off)) = offsets.iter().find(|(oid, _)| *oid == id) {
                pdf.extend_from_slice(format!("{:010} 00000 n \n", off).as_bytes());
            } else {
                pdf.extend_from_slice(b"0000000000 65535 f \n");
            }
        }
        pdf.extend_from_slice(
            format!(
                "trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{}\n%%EOF\n",
                max_id + 1,
                xref_off
            )
            .as_bytes(),
        );
        pdf
    }

    #[test]
    fn decode_resolves_resource_name_cs() {
        // Image XObject with `/ColorSpace /CS0`; the page `/Resources/ColorSpace`
        // maps `/CS0 → /DeviceGray`. Before the fix, decode() failed with
        // "Unsupported color space: CS0"; now it succeeds.
        let doc = crate::document::PdfDocument::from_bytes(pdf_with_image_xobject("/CS0", &[128]))
            .unwrap();
        let obj_ref = ObjectRef::new(99, 0);
        let xobj = doc.load_object(obj_ref).unwrap();
        let dict = xobj.as_dict().expect("image xobject dict").clone();

        let mut map = empty_map();
        map.insert("CS0".to_string(), Object::Name("DeviceGray".to_string()));

        let handle = image_handle_from_xobject(
            &doc,
            obj_ref,
            &dict,
            crate::content::Matrix::identity(),
            0,
            &map,
        )
        .expect("handle builds");

        assert_eq!(handle.color_space, ColorSpace::DeviceGray);
        assert!(handle.indexed_base().is_none());
        // decode() must now resolve /CS0 via the stored resource map.
        let image = handle.decode().expect("decode resolves resource-name CS");
        assert_eq!(*image.color_space(), ColorSpace::DeviceGray);
    }

    #[test]
    fn xobject_direct_indexed_handle_reports_indexed_with_base() {
        let doc = crate::document::PdfDocument::from_bytes(pdf_with_image_xobject(
            "[/Indexed /DeviceRGB 1 <000000FFFFFF>]",
            &[0],
        ))
        .unwrap();
        let obj_ref = ObjectRef::new(99, 0);
        let dict = doc.load_object(obj_ref).unwrap().as_dict().unwrap().clone();
        let handle = image_handle_from_xobject(
            &doc,
            obj_ref,
            &dict,
            crate::content::Matrix::identity(),
            0,
            &empty_map(),
        )
        .unwrap();
        assert_eq!(handle.color_space, ColorSpace::Indexed);
        assert_eq!(handle.indexed_base(), Some(ColorSpace::DeviceRGB));
    }
}