printpdf 0.9.1

Rust library for reading and writing PDF files
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
use core::fmt;
use std::io::Cursor;

use image::{DynamicImage, GenericImageView};

use crate::{ColorBits, ColorSpace, PdfWarnMsg};

// Re-export types from image_types
pub use crate::image_types::{
    ImageOptimizationOptions, ImageCompression, OutputImageFormat,
    RawImage, RawImageData, RawImageFormat,
};

struct RawImageU8 {
    pub pixels: Vec<u8>,
    pub width: usize,
    pub height: usize,
    pub data_format: RawImageFormat,
}

impl fmt::Debug for RawImageU8 {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RawImageU8")
            .field("pixels", &self.pixels.len())
            .field("width", &self.width)
            .field("height", &self.height)
            .field("data_format", &self.data_format)
            .finish()
    }
}

impl RawImageFormat {
    pub fn reduce_to_rgb(&self) -> Self {
        use RawImageFormat::*;
        match self {
            RGBA8 => RGB8,
            RGBA16 => RGB16,
            RGBAF32 => RGBF32,
            RG8 => R8,
            RG16 => R16,
            other => *other,
        }
    }

    pub fn has_alpha(&self) -> bool {
        use RawImageFormat::*;
        matches!(self, RGBA8 | RGBA16 | RGBAF32 | RG8 | RG16)
    }

    pub fn get_color_bits_and_space(&self) -> (ColorBits, ColorSpace) {
        use self::RawImageFormat::*;
        match self {
            R8 => (ColorBits::Bit8, ColorSpace::Greyscale),
            RG8 => (ColorBits::Bit8, ColorSpace::GreyscaleAlpha),
            RGB8 => (ColorBits::Bit8, ColorSpace::Rgb),
            RGBA8 => (ColorBits::Bit8, ColorSpace::Rgba),
            R16 => (ColorBits::Bit16, ColorSpace::Greyscale),
            RG16 => (ColorBits::Bit16, ColorSpace::GreyscaleAlpha),
            RGB16 => (ColorBits::Bit16, ColorSpace::Rgb),
            RGBA16 => (ColorBits::Bit16, ColorSpace::Rgba),
            BGR8 => (ColorBits::Bit8, ColorSpace::Rgb),
            BGRA8 => (ColorBits::Bit8, ColorSpace::Rgba),
            RGBF32 => (ColorBits::Bit16, ColorSpace::Rgb),
            RGBAF32 => (ColorBits::Bit16, ColorSpace::Rgba),
        }
    }
}

impl RawImageData {
    pub fn empty(format: RawImageFormat) -> Self {
        use self::RawImageFormat::*;
        match format {
            R8 | RG8 | RGB8 | RGBA8 | BGR8 | BGRA8 => Self::U8(Vec::new()),

            R16 | RG16 | RGB16 | RGBA16 => Self::U16(Vec::new()),

            RGBF32 | RGBAF32 => Self::F32(Vec::new()),
        }
    }

    pub fn is_empty(&self) -> bool {
        match self {
            RawImageData::U8(vec) => vec.is_empty(),
            RawImageData::U16(vec) => vec.is_empty(),
            RawImageData::F32(vec) => vec.is_empty(),
        }
    }
}

/// Parses a size string like "300kb" into bytes
pub fn parse_size_string(size_str: &str) -> Result<usize, String> {
    let size_str = size_str.trim().to_lowercase();
    let numeric_part: String = size_str
        .chars()
        .take_while(|c| c.is_digit(10) || *c == '.')
        .collect();
    let unit_part: String = size_str.chars().skip(numeric_part.len()).collect();

    let num = numeric_part
        .parse::<f64>()
        .map_err(|e| format!("Invalid size number: {}", e))?;

    let multiplier = match unit_part.as_str() {
        "b" => 1,
        "kb" | "k" => 1024,
        "mb" | "m" => 1024 * 1024,
        "gb" | "g" => 1024 * 1024 * 1024,
        _ => return Err(format!("Unknown size unit: {}", unit_part)),
    };

    Ok((num * multiplier as f64) as usize)
}

impl RawImage {
    /// Creates an empty `RawImage`
    pub fn empty(width: usize, height: usize, format: crate::RawImageFormat) -> Self {
        Self {
            width,
            height,
            data_format: format,
            pixels: RawImageData::empty(format),
            tag: Vec::new(),
        }
    }

    /// Same as decode_from_bytes, but uses async for browser-native image decoding
    pub async fn decode_from_bytes_async(
        bytes: &[u8],
        warnings: &mut Vec<PdfWarnMsg>,
    ) -> Result<Self, String> {
        // Try browser-native decoding first for better format support
        #[cfg(all(feature = "js-sys", target_family = "wasm"))]
        {
            warnings.push(PdfWarnMsg::info(
                0,
                0,
                "Attempting browser-native image decoding".to_string(),
            ));
            if let Ok(image) = browser_image::decode_image_with_browser(bytes, warnings).await {
                warnings.push(PdfWarnMsg::info(
                    0,
                    0,
                    "Successfully used browser-native image decoder".to_string(),
                ));
                return Ok(image);
            }
            warnings.push(PdfWarnMsg::info(
                0,
                0,
                "Browser-native decoding failed, falling back to standard decode".to_string(),
            ));
        }

        Self::decode_from_bytes(bytes, warnings)
    }

    pub fn from_dynamic_image(image: DynamicImage) -> Result<Self, String> {
        let (w, h) = image.dimensions();
        let data_format = match image.color() {
            image::ColorType::L8 => RawImageFormat::R8,
            image::ColorType::La8 => RawImageFormat::RG8,
            image::ColorType::Rgb8 => RawImageFormat::RGB8,
            image::ColorType::Rgba8 => RawImageFormat::RGBA8,
            _ => return Err("Unsupported color type".to_string()),
        };

        let pixels = match image {
            DynamicImage::ImageLuma8(buf) => RawImageData::U8(buf.into_raw()),
            DynamicImage::ImageLumaA8(buf) => RawImageData::U8(buf.into_raw()),
            DynamicImage::ImageRgb8(buf) => RawImageData::U8(buf.into_raw()),
            DynamicImage::ImageRgba8(buf) => RawImageData::U8(buf.into_raw()),
            _ => return Err("Unsupported dynamic image format".to_string()),
        };

        Ok(RawImage {
            pixels,
            width: w as usize,
            height: h as usize,
            data_format,
            tag: Vec::new(),
        })
    }

    /// NOTE: depends on the enabled image formats!
    pub fn decode_from_bytes(bytes: &[u8], warnings: &mut Vec<PdfWarnMsg>) -> Result<Self, String> {
        use image::DynamicImage::*;

        let im = match image::guess_format(bytes) {
            Ok(format) => {
                warnings.push(PdfWarnMsg::info(
                    0,
                    0,
                    format!("Detected image format: {:?}", format),
                ));
                format
            }
            Err(e) => return Err(e.to_string()),
        };

        let b_len = bytes.len();
        warnings.push(PdfWarnMsg::info(
            0,
            0,
            format!("Image data size: {} bytes", b_len),
        ));

        // Check feature support for various formats
        #[cfg(not(feature = "gif"))]
        {
            let err = format!(
                "cannot decode image (len = {b_len} bytes): printpdf is missing feature 'gif' to \
                 decode GIF files. Please enable it or construct the RawImage manually."
            );
            if im == image::ImageFormat::Gif {
                warnings.push(PdfWarnMsg::warning(
                    0,
                    0,
                    "GIF format detected but GIF support not compiled in".to_string(),
                ));
                return Err(err);
            }
        }

        #[cfg(not(feature = "jpeg"))]
        {
            let err = format!(
                "cannot decode image (len = {b_len} bytes): printpdf is missing feature 'jpeg' to \
                 decode JPEG files. Please enable it or construct the RawImage manually."
            );
            if im == image::ImageFormat::Jpeg {
                warnings.push(PdfWarnMsg::warning(
                    0,
                    0,
                    "JPEG format detected but JPEG support not compiled in".to_string(),
                ));
                return Err(err);
            }
        }

        #[cfg(not(feature = "png"))]
        {
            let err = format!(
                "cannot decode image (len = {b_len} bytes): printpdf is missing feature 'png' to \
                 decode PNG files. Please enable it or construct the RawImage manually."
            );
            if im == image::ImageFormat::Png {
                warnings.push(PdfWarnMsg::warning(
                    0,
                    0,
                    "PNG format detected but PNG support not compiled in".to_string(),
                ));
                return Err(err);
            }
        }

        // Check additional image formats as in the original code...

        // Decode the image
        let im = match image::ImageReader::new(Cursor::new(bytes))
            .with_guessed_format()
            .map_err(|e| e.to_string())?
            .decode()
        {
            Ok(img) => img,
            Err(e) => {
                let err_msg = e.to_string();
                warnings.push(PdfWarnMsg::warning(
                    0,
                    0,
                    format!("Image decode error: {}", err_msg),
                ));
                return Err(err_msg);
            }
        };

        let (w, h) = im.dimensions();
        warnings.push(PdfWarnMsg::info(
            0,
            0,
            format!("Image dimensions: {}x{} pixels", w, h),
        ));

        // Map the color type with informative messages
        let ct = match im.color() {
            image::ColorType::L8 => {
                warnings.push(PdfWarnMsg::info(
                    0,
                    0,
                    "Detected grayscale (L8) image".to_string(),
                ));
                RawImageFormat::R8
            }
            image::ColorType::La8 => {
                warnings.push(PdfWarnMsg::info(
                    0,
                    0,
                    "Detected grayscale with alpha (La8) image".to_string(),
                ));
                RawImageFormat::RG8
            }
            image::ColorType::Rgb8 => {
                warnings.push(PdfWarnMsg::info(
                    0,
                    0,
                    "Detected RGB (Rgb8) image".to_string(),
                ));
                RawImageFormat::RGB8
            }
            image::ColorType::Rgba8 => {
                warnings.push(PdfWarnMsg::info(
                    0,
                    0,
                    "Detected RGBA (Rgba8) image".to_string(),
                ));
                RawImageFormat::RGBA8
            }
            image::ColorType::L16 => {
                warnings.push(PdfWarnMsg::info(
                    0,
                    0,
                    "Detected 16-bit grayscale (L16) image".to_string(),
                ));
                RawImageFormat::R16
            }
            image::ColorType::La16 => {
                warnings.push(PdfWarnMsg::info(
                    0,
                    0,
                    "Detected 16-bit grayscale with alpha (La16) image".to_string(),
                ));
                RawImageFormat::RG16
            }
            image::ColorType::Rgb16 => {
                warnings.push(PdfWarnMsg::info(
                    0,
                    0,
                    "Detected 16-bit RGB (Rgb16) image".to_string(),
                ));
                RawImageFormat::RGB16
            }
            image::ColorType::Rgba16 => {
                warnings.push(PdfWarnMsg::info(
                    0,
                    0,
                    "Detected 16-bit RGBA (Rgba16) image".to_string(),
                ));
                RawImageFormat::RGBA16
            }
            image::ColorType::Rgb32F => {
                warnings.push(PdfWarnMsg::info(
                    0,
                    0,
                    "Detected 32-bit float RGB (Rgb32F) image".to_string(),
                ));
                RawImageFormat::RGBF32
            }
            image::ColorType::Rgba32F => {
                warnings.push(PdfWarnMsg::info(
                    0,
                    0,
                    "Detected 32-bit float RGBA (Rgba32F) image".to_string(),
                ));
                RawImageFormat::RGBAF32
            }
            other => {
                let err_msg = format!("Unsupported color type: {:?}", other);
                warnings.push(PdfWarnMsg::warning(0, 0, err_msg.clone()));
                return Err("invalid raw image format".to_string());
            }
        };

        // Extract pixel data
        let pixels = match im {
            ImageLuma8(image_buffer) => {
                warnings.push(PdfWarnMsg::info(
                    0,
                    0,
                    format!(
                        "Converting ImageLuma8 buffer of {} pixels",
                        image_buffer.len()
                    ),
                ));
                RawImageData::U8(image_buffer.into_raw())
            }
            ImageLumaA8(image_buffer) => {
                warnings.push(PdfWarnMsg::info(
                    0,
                    0,
                    format!(
                        "Converting ImageLumaA8 buffer of {} pixels",
                        image_buffer.len()
                    ),
                ));
                RawImageData::U8(image_buffer.into_raw())
            }
            ImageRgb8(image_buffer) => {
                warnings.push(PdfWarnMsg::info(
                    0,
                    0,
                    format!(
                        "Converting ImageRgb8 buffer of {} pixels",
                        image_buffer.len()
                    ),
                ));
                RawImageData::U8(image_buffer.into_raw())
            }
            ImageRgba8(image_buffer) => {
                warnings.push(PdfWarnMsg::info(
                    0,
                    0,
                    format!(
                        "Converting ImageRgba8 buffer of {} pixels",
                        image_buffer.len()
                    ),
                ));
                RawImageData::U8(image_buffer.into_raw())
            }
            ImageLuma16(image_buffer) => {
                warnings.push(PdfWarnMsg::info(
                    0,
                    0,
                    format!(
                        "Converting ImageLuma16 buffer of {} pixels",
                        image_buffer.len()
                    ),
                ));
                RawImageData::U16(image_buffer.into_raw())
            }
            ImageLumaA16(image_buffer) => {
                warnings.push(PdfWarnMsg::info(
                    0,
                    0,
                    format!(
                        "Converting ImageLumaA16 buffer of {} pixels",
                        image_buffer.len()
                    ),
                ));
                RawImageData::U16(image_buffer.into_raw())
            }
            ImageRgb16(image_buffer) => {
                warnings.push(PdfWarnMsg::info(
                    0,
                    0,
                    format!(
                        "Converting ImageRgb16 buffer of {} pixels",
                        image_buffer.len()
                    ),
                ));
                RawImageData::U16(image_buffer.into_raw())
            }
            ImageRgba16(image_buffer) => {
                warnings.push(PdfWarnMsg::info(
                    0,
                    0,
                    format!(
                        "Converting ImageRgba16 buffer of {} pixels",
                        image_buffer.len()
                    ),
                ));
                RawImageData::U16(image_buffer.into_raw())
            }
            ImageRgb32F(image_buffer) => {
                warnings.push(PdfWarnMsg::info(
                    0,
                    0,
                    format!(
                        "Converting ImageRgb32F buffer of {} pixels",
                        image_buffer.len()
                    ),
                ));
                RawImageData::F32(image_buffer.into_raw())
            }
            ImageRgba32F(image_buffer) => {
                warnings.push(PdfWarnMsg::info(
                    0,
                    0,
                    format!(
                        "Converting ImageRgba32F buffer of {} pixels",
                        image_buffer.len()
                    ),
                ));
                RawImageData::F32(image_buffer.into_raw())
            }
            _ => {
                warnings.push(PdfWarnMsg::warning(
                    0,
                    0,
                    "Invalid pixel format".to_string(),
                ));
                return Err("invalid pixel format".to_string());
            }
        };

        warnings.push(PdfWarnMsg::info(
            0,
            0,
            "Image decoded successfully".to_string(),
        ));

        Ok(RawImage {
            pixels,
            width: w as usize,
            height: h as usize,
            data_format: ct,
            tag: Vec::new(),
        })
    }
    pub async fn encode_to_bytes_async(
        &self,
        target_fmt: &[OutputImageFormat],
    ) -> Result<(Vec<u8>, OutputImageFormat), String> {
        #[cfg(all(feature = "js-sys", target_family = "wasm"))]
        for f in target_fmt {
            if let Ok(bytes) = browser_image::encode_image_with_browser(self, *f).await {
                return Ok((bytes, *f));
            }
        }

        self.encode_to_bytes(target_fmt)
    }
    /// NOTE: depends on the enabled image formats!
    ///
    /// Function will try to encode the image to the given formats and return an Error on
    /// exhaustion. Tries to encode the image into one of the given target formats, returning
    /// the encoded bytes if successful. For simplicity this implementation supports only 8‑bit
    /// image data.
    pub fn encode_to_bytes(
        &self,
        target_fmt: &[OutputImageFormat],
    ) -> Result<(Vec<u8>, OutputImageFormat), String> {
        // For this example we only support the U8 variant.
        let dyn_image = match (&self.pixels, self.data_format) {
            (RawImageData::U8(ref vec), RawImageFormat::R8) => {
                image::GrayImage::from_raw(self.width as u32, self.height as u32, vec.clone())
                    .map(DynamicImage::ImageLuma8)
            }
            (RawImageData::U8(ref vec), RawImageFormat::RG8) => {
                image::ImageBuffer::from_raw(self.width as u32, self.height as u32, vec.clone())
                    .map(|buf: image::ImageBuffer<image::LumaA<u8>, Vec<u8>>| {
                        DynamicImage::ImageLumaA8(buf)
                    })
            }
            (RawImageData::U8(ref vec), RawImageFormat::RGB8) => {
                image::RgbImage::from_raw(self.width as u32, self.height as u32, vec.clone())
                    .map(DynamicImage::ImageRgb8)
            }
            (RawImageData::U8(ref vec), RawImageFormat::RGBA8) => {
                image::RgbaImage::from_raw(self.width as u32, self.height as u32, vec.clone())
                    .map(DynamicImage::ImageRgba8)
            }
            _ => None,
        }
        .ok_or_else(|| {
            "Failed to construct dynamic image (unsupported pixel format?)".to_string()
        })?;

        // Try each target format in order.
        for fmt in target_fmt {
            use image::ImageFormat;
            let image_fmt = match fmt {
                OutputImageFormat::Png => ImageFormat::Png,
                OutputImageFormat::Jpeg => ImageFormat::Jpeg,
                OutputImageFormat::Gif => ImageFormat::Gif,
                OutputImageFormat::Webp => ImageFormat::WebP,
                OutputImageFormat::Pnm => ImageFormat::Pnm,
                OutputImageFormat::Tiff => ImageFormat::Tiff,
                OutputImageFormat::Tga => ImageFormat::Tga,
                OutputImageFormat::Bmp => ImageFormat::Bmp,
                OutputImageFormat::Avif => ImageFormat::Avif,
            };
            let mut buf = Vec::new();
            if dyn_image
                .write_to(&mut Cursor::new(&mut buf), image_fmt)
                .is_ok()
            {
                return Ok((buf, *fmt));
            }
        }

        Err("Could not encode image in any of the requested target formats".to_string())
    }

    /// Optimizes the image based on the provided options
    pub fn optimize(&mut self, options: &ImageOptimizationOptions) -> Result<(), String> {
        // Remove alpha channel if all pixels are opaque and auto-optimize is enabled
        if options.auto_optimize.unwrap_or_default() && self.data_format.has_alpha() {
            if self.is_fully_opaque() {
                self.remove_alpha_channel()?;
            }
        }

        // Check if color image is actually greyscale
        if options.auto_optimize.unwrap_or_default()
            && self.is_color_format()
            && self.is_actually_greyscale()
        {
            self.convert_to_greyscale()?;
        }

        // NEW: Convert to greyscale if both auto_optimize and convert_to_greyscale are true
        if options.auto_optimize.unwrap_or_default()
            && options.convert_to_greyscale.unwrap_or_default()
            && self.is_color_format()
        {
            self.convert_to_greyscale()?;
        }

        // Apply dithering to greyscale images if requested
        if options.dither_greyscale.unwrap_or_default() && self.is_greyscale_format() {
            self.apply_dithering()?;
        }

        // Resize image if it exceeds max size
        if let Some(max_size) = options
            .max_image_size
            .as_deref()
            .and_then(|s| parse_size_string(s).ok())
        {
            let current_size = self.estimate_size_bytes();
            if current_size > max_size {
                self.resize_to_fit_size(max_size)?;
            }
        }

        Ok(())
    }

    /// Checks if all pixels in the alpha channel are fully opaque
    pub fn is_fully_opaque(&self) -> bool {
        match &self.pixels {
            RawImageData::U8(data) => match self.data_format {
                RawImageFormat::RGBA8 => {
                    for i in 3..data.len() as usize {
                        if i % 4 == 3 && data[i] != 255 {
                            return false;
                        }
                    }
                    true
                }
                RawImageFormat::BGRA8 => {
                    for i in 3..data.len() as usize {
                        if i % 4 == 3 && data[i] != 255 {
                            return false;
                        }
                    }
                    true
                }
                _ => false,
            },
            RawImageData::U16(data) => match self.data_format {
                RawImageFormat::RGBA16 => {
                    for i in 3..data.len() as usize {
                        if i % 4 == 3 && data[i] != 65535 {
                            return false;
                        }
                    }
                    true
                }
                _ => false,
            },
            RawImageData::F32(data) => match self.data_format {
                RawImageFormat::RGBAF32 => {
                    for i in 3..data.len() as usize {
                        if i % 4 == 3 && data[i] < 0.999 {
                            return false;
                        }
                    }
                    true
                }
                _ => false,
            },
        }
    }

    /// Removes the alpha channel from images that have one
    pub fn remove_alpha_channel(&mut self) -> Result<(), String> {
        self.pixels = match (&self.pixels, self.data_format) {
            (RawImageData::U8(data), RawImageFormat::RGBA8) => {
                let mut rgb = Vec::with_capacity(data.len() / 4 * 3);
                for i in (0..data.len()).step_by(4) {
                    if i + 2 < data.len() {
                        rgb.push(data[i]);
                        rgb.push(data[i + 1]);
                        rgb.push(data[i + 2]);
                    }
                }
                self.data_format = RawImageFormat::RGB8;
                RawImageData::U8(rgb)
            }
            (RawImageData::U8(data), RawImageFormat::BGRA8) => {
                let mut bgr = Vec::with_capacity(data.len() / 4 * 3);
                for i in (0..data.len()).step_by(4) {
                    if i + 2 < data.len() {
                        bgr.push(data[i]);
                        bgr.push(data[i + 1]);
                        bgr.push(data[i + 2]);
                    }
                }
                self.data_format = RawImageFormat::BGR8;
                RawImageData::U8(bgr)
            }
            (RawImageData::U16(data), RawImageFormat::RGBA16) => {
                let mut rgb = Vec::with_capacity(data.len() / 4 * 3);
                for i in (0..data.len()).step_by(4) {
                    if i + 2 < data.len() {
                        rgb.push(data[i]);
                        rgb.push(data[i + 1]);
                        rgb.push(data[i + 2]);
                    }
                }
                self.data_format = RawImageFormat::RGB16;
                RawImageData::U16(rgb)
            }
            (RawImageData::F32(data), RawImageFormat::RGBAF32) => {
                let mut rgb = Vec::with_capacity(data.len() / 4 * 3);
                for i in (0..data.len()).step_by(4) {
                    if i + 2 < data.len() {
                        rgb.push(data[i]);
                        rgb.push(data[i + 1]);
                        rgb.push(data[i + 2]);
                    }
                }
                self.data_format = RawImageFormat::RGBF32;
                RawImageData::F32(rgb)
            }
            _ => return Err("Image doesn't have an alpha channel".to_string()),
        };

        Ok(())
    }

    /// Returns true if the image is in an RGB color format
    pub fn is_color_format(&self) -> bool {
        match self.data_format {
            RawImageFormat::RGB8
            | RawImageFormat::RGBA8
            | RawImageFormat::BGR8
            | RawImageFormat::BGRA8
            | RawImageFormat::RGB16
            | RawImageFormat::RGBA16
            | RawImageFormat::RGBF32
            | RawImageFormat::RGBAF32 => true,
            _ => false,
        }
    }

    /// Returns true if the image is in a greyscale format
    pub fn is_greyscale_format(&self) -> bool {
        match self.data_format {
            RawImageFormat::R8
            | RawImageFormat::RG8
            | RawImageFormat::R16
            | RawImageFormat::RG16 => true,
            _ => false,
        }
    }

    /// Checks if an RGB image actually has only greyscale content
    pub fn is_actually_greyscale(&self) -> bool {
        match (&self.pixels, self.data_format) {
            (RawImageData::U8(data), RawImageFormat::RGB8)
            | (RawImageData::U8(data), RawImageFormat::BGR8) => {
                for i in (0..data.len()).step_by(3) {
                    if i + 2 < data.len() {
                        let ch1 = data[i];
                        let ch2 = data[i + 1];
                        let ch3 = data[i + 2];

                        // Allow small differences in color channels (accounting for compression
                        // artifacts)
                        if (ch1 as i16 - ch2 as i16).abs() > 3
                            || (ch1 as i16 - ch3 as i16).abs() > 3
                            || (ch2 as i16 - ch3 as i16).abs() > 3
                        {
                            return false;
                        }
                    }
                }
                true
            }
            (RawImageData::U8(data), RawImageFormat::RGBA8)
            | (RawImageData::U8(data), RawImageFormat::BGRA8) => {
                for i in (0..data.len()).step_by(4) {
                    if i + 2 < data.len() {
                        let ch1 = data[i];
                        let ch2 = data[i + 1];
                        let ch3 = data[i + 2];

                        if (ch1 as i16 - ch2 as i16).abs() > 3
                            || (ch1 as i16 - ch3 as i16).abs() > 3
                            || (ch2 as i16 - ch3 as i16).abs() > 3
                        {
                            return false;
                        }
                    }
                }
                true
            }
            (RawImageData::U16(data), RawImageFormat::RGB16)
            | (RawImageData::U16(data), RawImageFormat::RGBA16) => {
                for i in (0..data.len()).step_by(if self.data_format == RawImageFormat::RGBA16 {
                    4
                } else {
                    3
                }) {
                    if i + 2 < data.len() {
                        let ch1 = data[i];
                        let ch2 = data[i + 1];
                        let ch3 = data[i + 2];

                        // Allow slightly larger differences for 16-bit
                        if (ch1 as i32 - ch2 as i32).abs() > 768
                            || (ch1 as i32 - ch3 as i32).abs() > 768
                            || (ch2 as i32 - ch3 as i32).abs() > 768
                        {
                            return false;
                        }
                    }
                }
                true
            }
            _ => false,
        }
    }

    /// Converts a color image to greyscale
    pub fn convert_to_greyscale(&mut self) -> Result<(), String> {
        self.pixels = match (&self.pixels, self.data_format) {
            (RawImageData::U8(data), RawImageFormat::RGB8) => {
                let mut grey = Vec::with_capacity(data.len() / 3);
                for i in (0..data.len()).step_by(3) {
                    if i + 2 < data.len() {
                        // Standard RGB to greyscale conversion weights
                        let g = (0.299 * data[i] as f32
                            + 0.587 * data[i + 1] as f32
                            + 0.114 * data[i + 2] as f32) as u8;
                        grey.push(g);
                    }
                }
                self.data_format = RawImageFormat::R8;
                RawImageData::U8(grey)
            }
            (RawImageData::U8(data), RawImageFormat::BGR8) => {
                let mut grey = Vec::with_capacity(data.len() / 3);
                for i in (0..data.len()).step_by(3) {
                    if i + 2 < data.len() {
                        // BGR to greyscale: note the different weight order
                        let g = (0.114 * data[i] as f32
                            + 0.587 * data[i + 1] as f32
                            + 0.299 * data[i + 2] as f32) as u8;
                        grey.push(g);
                    }
                }
                self.data_format = RawImageFormat::R8;
                RawImageData::U8(grey)
            }
            (RawImageData::U8(data), RawImageFormat::RGBA8) => {
                let mut grey_alpha = Vec::with_capacity(data.len() / 2);
                for i in (0..data.len()).step_by(4) {
                    if i + 3 < data.len() {
                        let g = (0.299 * data[i] as f32
                            + 0.587 * data[i + 1] as f32
                            + 0.114 * data[i + 2] as f32) as u8;
                        grey_alpha.push(g); // Grayscale value
                        grey_alpha.push(data[i + 3]); // Alpha value
                    }
                }
                self.data_format = RawImageFormat::RG8; // Use RG8 instead of R8
                RawImageData::U8(grey_alpha)
            }
            (RawImageData::U8(data), RawImageFormat::BGRA8) => {
                let mut grey_alpha = Vec::with_capacity(data.len() / 2);
                for i in (0..data.len()).step_by(4) {
                    if i + 3 < data.len() {
                        // BGR to greyscale: note the different weight order
                        let g = (0.114 * data[i] as f32
                            + 0.587 * data[i + 1] as f32
                            + 0.299 * data[i + 2] as f32) as u8;
                        grey_alpha.push(g); // Grayscale value
                        grey_alpha.push(data[i + 3]); // Alpha value
                    }
                }
                self.data_format = RawImageFormat::RG8;
                RawImageData::U8(grey_alpha)
            }
            (RawImageData::U16(data), RawImageFormat::RGB16) => {
                let mut grey = Vec::with_capacity(data.len() / 3);
                for i in (0..data.len()).step_by(3) {
                    if i + 2 < data.len() {
                        let g = (0.299 * data[i] as f32
                            + 0.587 * data[i + 1] as f32
                            + 0.114 * data[i + 2] as f32) as u16;
                        grey.push(g);
                    }
                }
                self.data_format = RawImageFormat::R16;
                RawImageData::U16(grey)
            }
            (RawImageData::U16(data), RawImageFormat::RGBA16) => {
                let mut grey_alpha = Vec::with_capacity(data.len() / 2);
                for i in (0..data.len()).step_by(4) {
                    if i + 3 < data.len() {
                        let g = (0.299 * data[i] as f32
                            + 0.587 * data[i + 1] as f32
                            + 0.114 * data[i + 2] as f32) as u16;
                        grey_alpha.push(g); // Grayscale value
                        grey_alpha.push(data[i + 3]); // Alpha value
                    }
                }
                self.data_format = RawImageFormat::RG16;
                RawImageData::U16(grey_alpha)
            }
            _ => return Err("Unsupported format for greyscale conversion".to_string()),
        };

        Ok(())
    }

    /// Applies Floyd-Steinberg dithering to a greyscale image
    pub fn apply_dithering(&mut self) -> Result<(), String> {
        if !self.is_greyscale_format() {
            return Err("Dithering can only be applied to greyscale images".to_string());
        }

        match (&mut self.pixels, self.data_format) {
            (RawImageData::U8(data), RawImageFormat::R8) => {
                // Create a mutable 2D grid for applying dithering
                let width = self.width;
                let height = self.height;
                let mut grid = Vec::with_capacity(height);

                // Convert linear data to 2D grid
                for y in 0..height {
                    let mut row = Vec::with_capacity(width);
                    for x in 0..width {
                        let idx = y * width + x;
                        if idx < data.len() {
                            row.push(data[idx] as i16);
                        } else {
                            row.push(0);
                        }
                    }
                    grid.push(row);
                }

                // Apply Floyd-Steinberg dithering
                for y in 0..height {
                    for x in 0..width {
                        let old_pixel = grid[y][x];
                        let new_pixel = if old_pixel > 127 { 255 } else { 0 };
                        let quant_error = old_pixel - new_pixel;

                        grid[y][x] = new_pixel;

                        // Distribute the error to neighboring pixels
                        if x + 1 < width {
                            grid[y][x + 1] = (grid[y][x + 1] + quant_error * 7 / 16).clamp(0, 255);
                        }

                        if y + 1 < height {
                            if x > 0 {
                                grid[y + 1][x - 1] =
                                    (grid[y + 1][x - 1] + quant_error * 3 / 16).clamp(0, 255);
                            }

                            grid[y + 1][x] = (grid[y + 1][x] + quant_error * 5 / 16).clamp(0, 255);

                            if x + 1 < width {
                                grid[y + 1][x + 1] =
                                    (grid[y + 1][x + 1] + quant_error * 1 / 16).clamp(0, 255);
                            }
                        }
                    }
                }

                // Convert back to linear data
                let mut result = Vec::with_capacity(data.len());
                for y in 0..height {
                    for x in 0..width {
                        result.push(grid[y][x] as u8);
                    }
                }

                // Update the original data
                *data = result;
                Ok(())
            }
            (RawImageData::U8(data), RawImageFormat::RG8) => {
                // For RG8 (grayscale+alpha), only dither the grayscale channel
                // Extract grayscale channel
                let mut grey = Vec::with_capacity(data.len() / 2);
                let mut alpha = Vec::with_capacity(data.len() / 2);

                for i in (0..data.len()).step_by(2) {
                    if i + 1 < data.len() {
                        grey.push(data[i]);
                        alpha.push(data[i + 1]);
                    }
                }

                // Create a temporary R8 image for dithering
                let mut temp_img = RawImage {
                    pixels: RawImageData::U8(grey),
                    width: self.width,
                    height: self.height,
                    data_format: RawImageFormat::R8,
                    tag: Vec::new(),
                };

                // Apply dithering to the temporary image
                temp_img.apply_dithering()?;

                // Recombine the channels
                if let RawImageData::U8(dithered_grey) = &temp_img.pixels {
                    let mut combined = Vec::with_capacity(data.len());
                    for i in 0..dithered_grey.len() {
                        if i < dithered_grey.len() && i < alpha.len() {
                            combined.push(dithered_grey[i]);
                            combined.push(alpha[i]);
                        }
                    }
                    *data = combined;
                }

                Ok(())
            }
            (RawImageData::U16(data), RawImageFormat::R16) => {
                // Dithering for 16-bit grayscale, convert to 8-bit for dithering and back to 16-bit
                let mut grey_u8 = Vec::with_capacity(data.len());

                // Convert 16-bit to 8-bit
                for &value in data.iter() {
                    grey_u8.push((value >> 8) as u8);
                }

                // Create a temporary R8 image for dithering
                let mut temp_img = RawImage {
                    pixels: RawImageData::U8(grey_u8),
                    width: self.width,
                    height: self.height,
                    data_format: RawImageFormat::R8,
                    tag: Vec::new(),
                };

                // Apply dithering to the temporary image
                temp_img.apply_dithering()?;

                // Convert back to 16-bit
                if let RawImageData::U8(dithered_grey) = &temp_img.pixels {
                    let mut result = Vec::with_capacity(data.len());
                    for &value in dithered_grey.iter() {
                        // Expand 8-bit to 16-bit
                        result.push((value as u16) << 8 | (value as u16));
                    }
                    *data = result;
                }

                Ok(())
            }
            _ => Err("Unsupported format for dithering".to_string()),
        }
    }

    /// Estimates the size of the image in bytes (uncompressed)
    pub fn estimate_size_bytes(&self) -> usize {
        let bits_per_pixel = match self.data_format {
            RawImageFormat::R8 => 8,
            RawImageFormat::RG8 => 16,
            RawImageFormat::RGB8 | RawImageFormat::BGR8 => 24,
            RawImageFormat::RGBA8 | RawImageFormat::BGRA8 => 32,
            RawImageFormat::R16 => 16,
            RawImageFormat::RG16 => 32,
            RawImageFormat::RGB16 => 48,
            RawImageFormat::RGBA16 => 64,
            RawImageFormat::RGBF32 => 96,   // 3 * 32 bits
            RawImageFormat::RGBAF32 => 128, // 4 * 32 bits
        };

        // Calculate size in bytes (rounded up to nearest byte)
        (self.width * self.height * bits_per_pixel + 7) / 8
    }

    /// Resizes the image to fit within a maximum size in bytes
    pub fn resize_to_fit_size(&mut self, max_size_bytes: usize) -> Result<(), String> {
        let current_size = self.estimate_size_bytes();
        if current_size <= max_size_bytes {
            // Already small enough
            return Ok(());
        }

        // Calculate the scaling factor needed to fit within max_size
        let scale_factor = (max_size_bytes as f64 / current_size as f64).sqrt();

        // Calculate new dimensions
        let new_width = (self.width as f64 * scale_factor).round() as usize;
        let new_height = (self.height as f64 * scale_factor).round() as usize;

        // Ensure new dimensions are at least 1 pixel
        let new_width = new_width.max(1);
        let new_height = new_height.max(1);

        match (&self.pixels, self.data_format) {
            (RawImageData::U8(data), RawImageFormat::RGB8) => {
                let mut new_data = Vec::with_capacity(new_width * new_height * 3);
                for y in 0..new_height {
                    for x in 0..new_width {
                        // Map new coordinates to old coordinates (nearest neighbor)
                        let old_x = (x as f64 * self.width as f64 / new_width as f64) as usize;
                        let old_y = (y as f64 * self.height as f64 / new_height as f64) as usize;
                        let old_idx = (old_y * self.width + old_x) * 3;

                        if old_idx + 2 < data.len() {
                            new_data.push(data[old_idx]);
                            new_data.push(data[old_idx + 1]);
                            new_data.push(data[old_idx + 2]);
                        } else {
                            new_data.push(0);
                            new_data.push(0);
                            new_data.push(0);
                        }
                    }
                }
                self.pixels = RawImageData::U8(new_data);
                self.width = new_width;
                self.height = new_height;
                Ok(())
            }
            (RawImageData::U8(data), RawImageFormat::RGBA8) => {
                let mut new_data = Vec::with_capacity(new_width * new_height * 4);
                for y in 0..new_height {
                    for x in 0..new_width {
                        let old_x = (x as f64 * self.width as f64 / new_width as f64) as usize;
                        let old_y = (y as f64 * self.height as f64 / new_height as f64) as usize;
                        let old_idx = (old_y * self.width + old_x) * 4;

                        if old_idx + 3 < data.len() {
                            new_data.push(data[old_idx]);
                            new_data.push(data[old_idx + 1]);
                            new_data.push(data[old_idx + 2]);
                            new_data.push(data[old_idx + 3]);
                        } else {
                            new_data.push(0);
                            new_data.push(0);
                            new_data.push(0);
                            new_data.push(0);
                        }
                    }
                }
                self.pixels = RawImageData::U8(new_data);
                self.width = new_width;
                self.height = new_height;
                Ok(())
            }
            (RawImageData::U8(data), RawImageFormat::BGR8) => {
                let mut new_data = Vec::with_capacity(new_width * new_height * 3);
                for y in 0..new_height {
                    for x in 0..new_width {
                        let old_x = (x as f64 * self.width as f64 / new_width as f64) as usize;
                        let old_y = (y as f64 * self.height as f64 / new_height as f64) as usize;
                        let old_idx = (old_y * self.width + old_x) * 3;

                        if old_idx + 2 < data.len() {
                            new_data.push(data[old_idx]);
                            new_data.push(data[old_idx + 1]);
                            new_data.push(data[old_idx + 2]);
                        } else {
                            new_data.push(0);
                            new_data.push(0);
                            new_data.push(0);
                        }
                    }
                }
                self.pixels = RawImageData::U8(new_data);
                self.width = new_width;
                self.height = new_height;
                Ok(())
            }
            (RawImageData::U8(data), RawImageFormat::BGRA8) => {
                let mut new_data = Vec::with_capacity(new_width * new_height * 4);
                for y in 0..new_height {
                    for x in 0..new_width {
                        let old_x = (x as f64 * self.width as f64 / new_width as f64) as usize;
                        let old_y = (y as f64 * self.height as f64 / new_height as f64) as usize;
                        let old_idx = (old_y * self.width + old_x) * 4;

                        if old_idx + 3 < data.len() {
                            new_data.push(data[old_idx]);
                            new_data.push(data[old_idx + 1]);
                            new_data.push(data[old_idx + 2]);
                            new_data.push(data[old_idx + 3]);
                        } else {
                            new_data.push(0);
                            new_data.push(0);
                            new_data.push(0);
                            new_data.push(0);
                        }
                    }
                }
                self.pixels = RawImageData::U8(new_data);
                self.width = new_width;
                self.height = new_height;
                Ok(())
            }
            (RawImageData::U8(data), RawImageFormat::R8) => {
                let mut new_data = Vec::with_capacity(new_width * new_height);
                for y in 0..new_height {
                    for x in 0..new_width {
                        let old_x = (x as f64 * self.width as f64 / new_width as f64) as usize;
                        let old_y = (y as f64 * self.height as f64 / new_height as f64) as usize;
                        let old_idx = old_y * self.width + old_x;

                        if old_idx < data.len() {
                            new_data.push(data[old_idx]);
                        } else {
                            new_data.push(0);
                        }
                    }
                }
                self.pixels = RawImageData::U8(new_data);
                self.width = new_width;
                self.height = new_height;
                Ok(())
            }
            (RawImageData::U8(data), RawImageFormat::RG8) => {
                let mut new_data = Vec::with_capacity(new_width * new_height * 2);
                for y in 0..new_height {
                    for x in 0..new_width {
                        let old_x = (x as f64 * self.width as f64 / new_width as f64) as usize;
                        let old_y = (y as f64 * self.height as f64 / new_height as f64) as usize;
                        let old_idx = (old_y * self.width + old_x) * 2;

                        if old_idx + 1 < data.len() {
                            new_data.push(data[old_idx]);
                            new_data.push(data[old_idx + 1]);
                        } else {
                            new_data.push(0);
                            new_data.push(0);
                        }
                    }
                }
                self.pixels = RawImageData::U8(new_data);
                self.width = new_width;
                self.height = new_height;
                Ok(())
            }
            _ => Err("Resize not implemented for this format".to_string()),
        }
    }
}

pub(crate) fn image_to_stream(
    im: RawImage,
    doc: &mut lopdf::Document,
    options: Option<&ImageOptimizationOptions>,
) -> lopdf::Stream {
    use lopdf::Object::*;

    // Optimize the image if options are provided
    let mut im = im;
    if let Some(opts) = options {
        let _ = im.optimize(opts);
    }

    let (rgb8, alpha) = split_rawimage_into_rgb_plus_alpha(im);
    let (bpc, cs) = rgb8.data_format.get_color_bits_and_space();
    let interpolate = false;

    let mut dict = lopdf::Dictionary::from_iter(vec![
        ("Type", Name("XObject".into())),
        ("Subtype", Name("Image".into())),
        ("Width", Integer(rgb8.width as i64)),
        ("Height", Integer(rgb8.height as i64)),
        ("BitsPerComponent", Integer(bpc.as_integer())),
        ("ColorSpace", Name(cs.as_string().into())),
        ("Interpolate", interpolate.into()),
    ]);

    // Apply compression filter based on options
    let mut compressed_pixels = rgb8.pixels.clone();
    if let Some(opts) = options {
        if let Some(filter) = get_compression_filter(opts, &rgb8) {
            match filter {
                #[cfg(feature = "jpeg")]
                "DCTDecode" => {
                    // JPEG compression
                    let quality = opts.quality.unwrap_or(0.85);
                    if let Some(jpeg_data) = jpeg_encode(&rgb8, quality) {
                        compressed_pixels = jpeg_data;
                        dict.set("Filter", Name(filter.into()));
                    }
                }
                "FlateDecode" => {
                    if let Some(flate_data) = flate_encode(&rgb8.pixels) {
                        compressed_pixels = flate_data;
                        dict.set("Filter", Name(filter.into()));
                    }
                }
                "LZWDecode" => {
                    if let Some(flate_data) = flate_encode(&rgb8.pixels) {
                        compressed_pixels = flate_data;
                        dict.set("Filter", Name("FlateDecode".into()));
                    }
                    /*
                    if let Some(lzw_data) = lzw_encode(&rgb8.pixels) {
                        compressed_pixels = lzw_data;
                        dict.set("Filter", Name(filter.into()));
                    }
                     */
                }
                "RunLengthDecode" => {
                    if let Some(flate_data) = flate_encode(&rgb8.pixels) {
                        compressed_pixels = flate_data;
                        dict.set("Filter", Name("FlateDecode".into()));
                    }
                    /*
                    if let Some(rle_data) = rle_encode(&rgb8.pixels) {
                        compressed_pixels = rle_data;
                        dict.set("Filter", Name(filter.into()));
                    }
                    */
                }
                _ => {}
            }
        }
    }

    // Handle alpha channel (SMask)
    if let Some(alpha) = alpha {
        let mut smask_dict = lopdf::Dictionary::from_iter(vec![
            ("Type", Name("XObject".into())),
            ("Subtype", Name("Image".into())),
            ("Width", Integer(rgb8.width as i64)),
            ("Height", Integer(rgb8.height as i64)),
            ("Interpolate", Boolean(false)),
            ("BitsPerComponent", Integer(ColorBits::Bit8.as_integer())),
            ("ColorSpace", Name(ColorSpace::Greyscale.as_string().into())),
        ]);

        // Alpha channel should typically use lossless compression
        let mut alpha_pixels = alpha.pixels.clone();
        let mut alpha_filter_applied = false;

        if let Some(opts) = options {
            // Get main image format or override with alpha-specific preference
            let format = opts.format.unwrap_or_default();

            // For lossy formats like JPEG, use Flate for alpha instead
            // For lossless formats, use the same compression as the main image
            let alpha_format = match format {
                ImageCompression::Auto | ImageCompression::Jpeg | ImageCompression::Jpeg2000 => {
                    ImageCompression::Flate // Use Flate for alpha by default with lossy formats
                }
                _ => format, // Use same lossless format as main image
            };

            match get_compression_filter_by_format(alpha_format) {
                "FlateDecode" => {
                    if let Some(flate_data) = flate_encode(&alpha_pixels) {
                        alpha_pixels = flate_data;
                        smask_dict.set("Filter", Name("FlateDecode".into()));
                        alpha_filter_applied = true;
                    }
                }
                "LZWDecode" => {
                    /*
                    if let Some(lzw_data) = lzw_encode(&alpha_pixels) {
                        alpha_pixels = lzw_data;
                        smask_dict.set("Filter", Name("LZWDecode".into()));
                        alpha_filter_applied = true;
                    }
                    */
                    if let Some(flate_data) = flate_encode(&rgb8.pixels) {
                        compressed_pixels = flate_data;
                        dict.set("Filter", Name("FlateDecode".into()));
                    }
                }
                "RunLengthDecode" => {
                    /*
                    if let Some(rle_data) = rle_encode(&alpha_pixels) {
                        alpha_pixels = rle_data;
                        smask_dict.set("Filter", Name("RunLengthDecode".into()));
                        alpha_filter_applied = true;
                    }
                    */
                    if let Some(flate_data) = flate_encode(&rgb8.pixels) {
                        compressed_pixels = flate_data;
                        dict.set("Filter", Name("FlateDecode".into()));
                    }
                }
                _ => {}
            }
        }

        // If no filter was applied yet, default to Flate
        if !alpha_filter_applied {
            if let Some(flate_data) = flate_encode(&alpha_pixels) {
                alpha_pixels = flate_data;
                smask_dict.set("Filter", Name("FlateDecode".into()));
            }
        }

        // Create stream with compression disabled (we already compressed the data)
        let mut stream = lopdf::Stream::new(smask_dict, alpha_pixels);
        stream = stream.with_compression(false);

        dict.set("SMask", Reference(doc.add_object(stream)));
    }

    // Create stream with compression disabled (we already compressed the data)
    let mut s = lopdf::Stream::new(dict, compressed_pixels);
    s = s.with_compression(false);

    s
}

// Function to select the appropriate compression filter
fn get_compression_filter(
    opts: &ImageOptimizationOptions,
    image: &RawImageU8,
) -> Option<&'static str> {
    let is_grayscale = matches!(image.data_format, RawImageFormat::R8 | RawImageFormat::RG8);
    let dithering_enabled = opts.dither_greyscale.unwrap_or_default();

    // Avoid DCT for grayscale images with dithering enabled
    if is_grayscale && dithering_enabled {
        return Some("LZWDecode"); // Use lossless compression for dithered grayscale
    }

    match opts.format.unwrap_or_default() {
        ImageCompression::Auto => {
            if matches!(image.data_format, RawImageFormat::R8 | RawImageFormat::RG8) {
                // For grayscale, LZW is often good
                Some("LZWDecode")
            } else {
                // For color images, DCT (JPEG) is usually the best choice
                #[cfg(feature = "jpeg")]
                {
                    Some("DCTDecode")
                }
                #[cfg(not(feature = "jpeg"))]
                {
                    Some("LZWDecode")
                }
            }
        }
        ImageCompression::Jpeg | ImageCompression::Jpeg2000 => {
            #[cfg(feature = "jpeg")]
            {
                Some("DCTDecode")
            }
            #[cfg(not(feature = "jpeg"))]
            {
                Some("LZWDecode")
            }
        }
        ImageCompression::Flate => Some("FlateDecode"),
        ImageCompression::Lzw => Some("LZWDecode"),
        ImageCompression::RunLength => Some("RunLengthDecode"),
        ImageCompression::None => None,
    }
}

// Get filter string directly from format
fn get_compression_filter_by_format(format: ImageCompression) -> &'static str {
    match format {
        ImageCompression::Auto => "FlateDecode",
        ImageCompression::Jpeg | ImageCompression::Jpeg2000 => {
            #[cfg(feature = "jpeg")]
            {
                "DCTDecode"
            }
            #[cfg(not(feature = "jpeg"))]
            {
                "LZWDecode"
            }
        }
        ImageCompression::Flate => "FlateDecode",
        ImageCompression::Lzw => "LZWDecode",
        ImageCompression::RunLength => "RunLengthDecode",
        ImageCompression::None => "FlateDecode",
    }
}

// JPEG encoding using the image crate
#[cfg(feature = "jpeg")]
fn jpeg_encode(image: &RawImageU8, quality: f32) -> Option<Vec<u8>> {
    let quality = (quality * 100.0) as u8;

    // Create a DynamicImage from the raw pixels
    let img = match image.data_format {
        RawImageFormat::RGB8 => image::RgbImage::from_raw(
            image.width as u32,
            image.height as u32,
            image.pixels.clone(),
        )
        .map(image::DynamicImage::ImageRgb8),
        RawImageFormat::R8 => image::GrayImage::from_raw(
            image.width as u32,
            image.height as u32,
            image.pixels.clone(),
        )
        .map(image::DynamicImage::ImageLuma8),
        RawImageFormat::BGR8 => {
            // Convert BGR to RGB
            let mut rgb_data = Vec::with_capacity(image.pixels.len());
            for chunk in image.pixels.chunks(3) {
                if chunk.len() == 3 {
                    rgb_data.push(chunk[2]); // R
                    rgb_data.push(chunk[1]); // G
                    rgb_data.push(chunk[0]); // B
                }
            }

            image::RgbImage::from_raw(image.width as u32, image.height as u32, rgb_data)
                .map(image::DynamicImage::ImageRgb8)
        }
        _ => None,
    }?;

    let mut jpeg_data = Vec::new();
    let mut cursor = std::io::Cursor::new(&mut jpeg_data);

    // Use image crate's JPEG encoder
    let encoder = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut cursor, quality);
    if img.write_with_encoder(encoder).is_ok() {
        Some(jpeg_data)
    } else {
        None
    }
}

// FLATE (deflate) encoding
fn flate_encode(data: &[u8]) -> Option<Vec<u8>> {
    use std::io::Write;

    use flate2::{write::ZlibEncoder, Compression};

    let mut encoder = ZlibEncoder::new(Vec::new(), Compression::best());
    encoder.write_all(data).ok()?;
    encoder.finish().ok()
}

// LZW encoding
#[allow(dead_code)]
fn lzw_encode(data: &[u8]) -> Option<Vec<u8>> {
    use weezl::{encode::Encoder, BitOrder};
    // Create encoder with MSB bit order (standard for PDF) and 8-bit code size
    let mut encoder = Encoder::new(BitOrder::Msb, 8);
    encoder.encode(data).ok()
}

// Simple Run Length Encoding implementation
#[allow(dead_code)]
fn rle_encode(data: &[u8]) -> Option<Vec<u8>> {
    let mut result = Vec::with_capacity(data.len());
    let mut i = 0;

    while i < data.len() {
        let mut run_length = 1;
        let current_byte = data[i];

        // Find run length (max 128)
        while i + run_length < data.len()
            && data[i + run_length] == current_byte
            && run_length < 128
        {
            run_length += 1;
        }

        if run_length > 1 {
            // Encode run: [length-1, byte]
            result.push((run_length - 1) as u8);
            result.push(current_byte);
            i += run_length;
        } else {
            // Find literals (max 128)
            let literal_start = i;
            let mut literal_count = 1;

            i += 1;

            while i < data.len()
                && (i + 1 >= data.len() || data[i] != data[i + 1])
                && literal_count < 128
            {
                literal_count += 1;
                i += 1;
            }

            // Encode literals: [257-length, byte1, byte2, ...]
            result.push((257 - literal_count) as u8);
            for j in 0..literal_count {
                result.push(data[literal_start + j]);
            }
        }
    }

    // End of data marker
    result.push(128);

    Some(result)
}

// If the image has an alpha channel, splits the alpha channel as a separate image
// to the used in the `/Smask` dictionary
fn split_rawimage_into_rgb_plus_alpha(im: RawImage) -> (RawImageU8, Option<RawImageU8>) {
    let has_alpha = im.data_format.has_alpha();
    let (orig, alpha) = if has_alpha {
        match im.data_format {
            // Existing handling for RGBA8/BGRA8 remains:
            RawImageFormat::RGBA8 => {
                if let RawImageData::U8(vec) = im.pixels {
                    let (rgb, alpha) = rgba_to_rgb(vec);
                    (rgb, alpha)
                } else {
                    (Vec::new(), Vec::new())
                }
            }
            RawImageFormat::BGRA8 => {
                if let RawImageData::U8(vec) = im.pixels {
                    let (bgr, alpha) = bgra_to_bgr(vec);
                    (bgr, alpha)
                } else {
                    (Vec::new(), Vec::new())
                }
            }
            RawImageFormat::RG8 => {
                if let RawImageData::U8(vec) = im.pixels {
                    let mut grey = Vec::with_capacity(vec.len() / 2);
                    let mut alpha = Vec::with_capacity(vec.len() / 2);
                    for i in (0..vec.len()).step_by(2) {
                        grey.push(vec[i]);
                        alpha.push(vec[i + 1]);
                    }
                    (grey, alpha)
                } else {
                    (Vec::new(), Vec::new())
                }
            }
            RawImageFormat::RG16 => {
                if let RawImageData::U16(vec) = im.pixels {
                    let mut grey = Vec::with_capacity(vec.len() / 2);
                    let mut alpha = Vec::with_capacity(vec.len() / 2);
                    for i in (0..vec.len()).step_by(2) {
                        grey.push(vec[i]);
                        alpha.push(vec[i + 1]);
                    }
                    (u16vec_to_u8(grey), u16vec_to_u8(alpha))
                } else {
                    (Vec::new(), Vec::new())
                }
            }
            _ => (Vec::new(), Vec::new()),
        }
    } else {
        match im.pixels {
            RawImageData::U8(vec) => (vec, Vec::new()),
            RawImageData::U16(vec) => (u16vec_to_u8(vec), Vec::new()),
            RawImageData::F32(vec) => (f32vec_to_u8(vec), Vec::new()),
        }
    };

    let orig = RawImageU8 {
        pixels: orig,
        width: im.width,
        height: im.height,
        data_format: im.data_format.reduce_to_rgb(),
    };

    let alpha_mask = if alpha.is_empty() {
        None
    } else {
        Some(RawImageU8 {
            pixels: alpha,
            width: im.width,
            height: im.height,
            data_format: RawImageFormat::R8,
        })
    };

    (orig, alpha_mask)
}

// Helper function to extract alpha channel from BGRA
fn bgra_to_bgr(rgba: Vec<u8>) -> (Vec<u8>, Vec<u8>) {
    let mut rgb = Vec::with_capacity(rgba.len() / 4 * 3);
    let mut alpha = Vec::with_capacity(rgba.len() / 4);

    for i in (0..rgba.len()).step_by(4) {
        if i + 3 < rgba.len() {
            rgb.push(rgba[i]); // B
            rgb.push(rgba[i + 1]); // G
            rgb.push(rgba[i + 2]); // R
            alpha.push(rgba[i + 3]); // A
        }
    }

    (rgb, alpha)
}

/// Takes a Vec<u8> of RGBA data and returns two Vec<u8> of RGB and alpha data
fn rgba_to_rgb(data: Vec<u8>) -> (Vec<u8>, Vec<u8>) {
    let mut rgb = Vec::with_capacity(data.len() / 4 * 3);
    let mut alpha = Vec::with_capacity(data.len() / 4);
    for i in (0..data.len()).step_by(4) {
        rgb.push(data[i]);
        rgb.push(data[i + 1]);
        rgb.push(data[i + 2]);
        alpha.push(data[i + 3]);
    }

    (rgb, alpha)
}

#[allow(dead_code)]
fn rgba_to_rgb16(data: Vec<u16>) -> (Vec<u16>, Vec<u16>) {
    let mut rgb = Vec::with_capacity(data.len() / 4 * 3);
    let mut alpha = Vec::with_capacity(data.len() / 4);
    for i in (0..data.len()).step_by(4) {
        rgb.push(data[i]);
        rgb.push(data[i + 1]);
        rgb.push(data[i + 2]);
        alpha.push(data[i + 3]);
    }

    (rgb, alpha)
}

#[allow(dead_code)]
fn rgba_to_rgbf32(data: Vec<f32>) -> (Vec<f32>, Vec<f32>) {
    let mut rgb = Vec::with_capacity(data.len() / 4 * 3);
    let mut alpha = Vec::with_capacity(data.len() / 4);
    for i in (0..data.len()).step_by(4) {
        rgb.push(data[i]);
        rgb.push(data[i + 1]);
        rgb.push(data[i + 2]);
        alpha.push(data[i + 3]);
    }

    (rgb, alpha)
}

fn u16vec_to_u8(data: Vec<u16>) -> Vec<u8> {
    data.iter().flat_map(|us| us.to_be_bytes()).collect()
}

fn f32vec_to_u8(data: Vec<f32>) -> Vec<u8> {
    data.iter().flat_map(|us| us.to_be_bytes()).collect()
}

#[cfg(all(feature = "js-sys", target_family = "wasm"))]
mod browser_image {

    use js_sys::{Array, Uint8Array};
    use wasm_bindgen::JsCast;
    use wasm_bindgen_futures::JsFuture;
    use web_sys::{
        js_sys, window, Blob, BlobPropertyBag, CanvasRenderingContext2d, HtmlCanvasElement,
        ImageBitmap,
    };

    use super::{OutputImageFormat, RawImage, RawImageData, RawImageFormat};
    use crate::PdfWarnMsg;

    // Decode image bytes using browser's capabilities
    pub async fn decode_image_with_browser(
        bytes: &[u8],
        _warnings: &mut Vec<PdfWarnMsg>,
    ) -> Result<RawImage, String> {
        let window = window().ok_or("No window available")?;

        // Create a Blob from the bytes
        let array = Array::new();
        let uint8_array = Uint8Array::from(bytes);
        array.push(&uint8_array.buffer());

        let options = BlobPropertyBag::new();
        let blob = Blob::new_with_u8_array_sequence_and_options(&array, &options)
            .map_err(|e| format!("Failed to create Blob: {:?}", e))?;

        // Create ImageBitmap from Blob
        let promise = window
            .create_image_bitmap_with_blob(&blob)
            .map_err(|e| format!("Failed to create ImageBitmap: {:?}", e))?;

        let bitmap: ImageBitmap = JsFuture::from(promise)
            .await
            .map_err(|e| format!("Promise rejected: {:?}", e))?
            .dyn_into()
            .map_err(|_| "Failed to cast to ImageBitmap")?;

        // Create a canvas to extract pixel data
        let document = window.document().ok_or("No document available")?;
        let canvas = document
            .create_element("canvas")
            .map_err(|_| "Failed to create canvas")?
            .dyn_into::<HtmlCanvasElement>()
            .map_err(|_| "Failed to cast to HtmlCanvasElement")?;

        let width = bitmap.width() as usize;
        let height = bitmap.height() as usize;

        canvas.set_width(width as u32);
        canvas.set_height(height as u32);

        let context = canvas
            .get_context("2d")
            .map_err(|_| "Failed to get context")?
            .ok_or("Context is null")?
            .dyn_into::<CanvasRenderingContext2d>()
            .map_err(|_| "Failed to cast to CanvasRenderingContext2d")?;

        context
            .draw_image_with_image_bitmap(&bitmap, 0.0, 0.0)
            .map_err(|_| "Failed to draw image")?;

        let image_data = context
            .get_image_data(0.0, 0.0, width as f64, height as f64)
            .map_err(|_| "Failed to get image data")?;

        let data = image_data.data();
        let data_vec = data.to_vec();

        // Convert to RawImage (RGBA8 format)
        Ok(RawImage {
            pixels: RawImageData::U8(data_vec),
            width,
            height,
            data_format: RawImageFormat::RGBA8,
            tag: Vec::new(),
        })
    }

    // Encode image to specific format using browser's Canvas API
    pub async fn encode_image_with_browser(
        image: &RawImage,
        format: OutputImageFormat,
    ) -> Result<Vec<u8>, String> {
        // Convert format to mime type
        let mime_type = match format {
            OutputImageFormat::Jpeg => "image/jpeg",
            OutputImageFormat::Png => "image/png",
            OutputImageFormat::Webp => "image/webp",
            _ => return Err(format!("Format {:?} not supported by browser", format)),
        };

        // Get pixel data
        let pixels = match &image.pixels {
            RawImageData::U8(data) => data,
            _ => return Err("Only U8 data is supported for browser encoding".to_string()),
        };

        // Set up canvas
        let window = window().ok_or("No window available")?;
        let document = window.document().ok_or("No document available")?;
        let canvas = document
            .create_element("canvas")
            .map_err(|_| "Failed to create canvas")?
            .dyn_into::<HtmlCanvasElement>()
            .map_err(|_| "Failed to cast to HtmlCanvasElement")?;

        canvas.set_width(image.width as u32);
        canvas.set_height(image.height as u32);

        let context = canvas
            .get_context("2d")
            .map_err(|_| "Failed to get context")?
            .ok_or("Context is null")?
            .dyn_into::<CanvasRenderingContext2d>()
            .map_err(|_| "Failed to cast to CanvasRenderingContext2d")?;

        // Create ImageData and put it on canvas
        let uint8_clamped_array = js_sys::Uint8ClampedArray::from(pixels.as_slice());
        let image_data = web_sys::ImageData::new_with_js_u8_clamped_array_and_sh(
            &uint8_clamped_array,
            image.width as u32,
            image.height as u32,
        )
        .map_err(|_| "Failed to create ImageData")?;

        context
            .put_image_data(&image_data, 0.0, 0.0)
            .map_err(|_| "Failed to put image data")?;

        // Get data URL
        let data_url = canvas
            .to_data_url_with_type(mime_type)
            .map_err(|_| format!("Failed to encode to {}", mime_type))?;

        // Extract binary data from data URL
        let bytes = crate::Base64OrRaw::B64(data_url).decode_bytes()?;

        Ok(bytes)
    }
}