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 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329
|
// ==========================================================
// FreeImage 3 .NET wrapper
// Original FreeImage 3 functions and .NET compatible derived functions
//
// Design and implementation by
// - Jean-Philippe Goerke (jpgoerke@users.sourceforge.net)
// - Carsten Klein (cklein05@users.sourceforge.net)
//
// Contributors:
// - David Boland (davidboland@vodafone.ie)
//
// Main reference : MSDN Knowlede Base
//
// This file is part of FreeImage 3
//
// COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES
// THAT THE COVERED CODE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE
// OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED
// CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT
// THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY
// SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL
// PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER
// THIS DISCLAIMER.
//
// Use at your own risk!
// ==========================================================
// ==========================================================
// CVS
// $Revision: 1.19 $
// $Date: 2011/10/02 13:00:45 $
// $Id: FreeImageWrapper.cs,v 1.19 2011/10/02 13:00:45 drolon Exp $
// ==========================================================
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using FreeImageAPI.IO;
using FreeImageAPI.Metadata;
namespace FreeImageAPI
{
/// <summary>
/// Static class importing functions from the FreeImage library
/// and providing additional functions.
/// </summary>
public static partial class FreeImage
{
#region Constants
/// <summary>
/// Array containing all 'FREE_IMAGE_MDMODEL's.
/// </summary>
public static readonly FREE_IMAGE_MDMODEL[] FREE_IMAGE_MDMODELS =
(FREE_IMAGE_MDMODEL[])Enum.GetValues(typeof(FREE_IMAGE_MDMODEL));
/// <summary>
/// Stores handles used to read from streams.
/// </summary>
private static Dictionary<FIMULTIBITMAP, fi_handle> streamHandles =
new Dictionary<FIMULTIBITMAP, fi_handle>();
/// <summary>
/// Version of the wrapper library.
/// </summary>
private static Version WrapperVersion;
private const int DIB_RGB_COLORS = 0;
private const int DIB_PAL_COLORS = 1;
private const int CBM_INIT = 0x4;
/// <summary>
/// An uncompressed format.
/// </summary>
public const int BI_RGB = 0;
/// <summary>
/// A run-length encoded (RLE) format for bitmaps with 8 bpp. The compression format is a 2-byte
/// format consisting of a count byte followed by a byte containing a color index.
/// </summary>
public const int BI_RLE8 = 1;
/// <summary>
/// An RLE format for bitmaps with 4 bpp. The compression format is a 2-byte format consisting
/// of a count byte followed by two word-length color indexes.
/// </summary>
public const int BI_RLE4 = 2;
/// <summary>
/// Specifies that the bitmap is not compressed and that the color table consists of three
/// <b>DWORD</b> color masks that specify the red, green, and blue components, respectively,
/// of each pixel. This is valid when used with 16- and 32-bpp bitmaps.
/// </summary>
public const int BI_BITFIELDS = 3;
/// <summary>
/// <b>Windows 98/Me, Windows 2000/XP:</b> Indicates that the image is a JPEG image.
/// </summary>
public const int BI_JPEG = 4;
/// <summary>
/// <b>Windows 98/Me, Windows 2000/XP:</b> Indicates that the image is a PNG image.
/// </summary>
public const int BI_PNG = 5;
#endregion
#region General functions
/// <summary>
/// Returns the internal version of this FreeImage .NET wrapper.
/// </summary>
/// <returns>The internal version of this FreeImage .NET wrapper.</returns>
public static Version GetWrapperVersion()
{
if (WrapperVersion == null)
{
try
{
object[] attributes = Assembly.GetAssembly(typeof(FreeImage))
.GetCustomAttributes(typeof(AssemblyFileVersionAttribute), false);
if ((attributes != null) && (attributes.Length != 0))
{
AssemblyFileVersionAttribute attribute =
attributes[0] as AssemblyFileVersionAttribute;
if ((attribute != null) && (attribute.Version != null))
{
return (WrapperVersion = new Version(attribute.Version));
}
}
}
catch
{
}
WrapperVersion = new Version();
}
return WrapperVersion;
}
/// <summary>
/// Returns the version of the native FreeImage library.
/// </summary>
/// <returns>The version of the native FreeImage library.</returns>
public static Version GetNativeVersion()
{
return new Version(GetVersion());
}
/// <summary>
/// Returns a value indicating if the FreeImage library is available or not.
/// See remarks for further details.
/// </summary>
/// <returns><c>false</c> if the file is not available or out of date;
/// <c>true</c>, otherwise.</returns>
/// <remarks>
/// The FreeImage.NET library is a wrapper for the native C++ library
/// (FreeImage.dll ... dont mix ist up with this library FreeImageNet.dll).
/// The native library <b>must</b> be either in the same folder as the program's
/// executable or in a folder contained in the envirent variable <i>PATH</i>
/// (for example %WINDIR%\System32).<para/>
/// Further more must both libraries, including the program itself,
/// be the same architecture (x86 or x64).
/// </remarks>
public static bool IsAvailable()
{
try
{
// Call a static fast executing function
Version nativeVersion = new Version(GetVersion());
Version wrapperVersion = GetWrapperVersion();
// No exception thrown, the library seems to be present
return
(nativeVersion.Major > wrapperVersion.Major) ||
((nativeVersion.Major == wrapperVersion.Major) && (nativeVersion.Minor > wrapperVersion.Minor)) ||
((nativeVersion.Major == wrapperVersion.Major) && (nativeVersion.Minor == wrapperVersion.Minor) && (nativeVersion.Build >= wrapperVersion.Build));
}
catch (DllNotFoundException)
{
return false;
}
catch (EntryPointNotFoundException)
{
return false;
}
catch (BadImageFormatException)
{
return false;
}
}
#endregion
#region Bitmap management functions
/// <summary>
/// Creates a new bitmap in memory.
/// </summary>
/// <param name="width">Width of the new bitmap.</param>
/// <param name="height">Height of the new bitmap.</param>
/// <param name="bpp">Bit depth of the new Bitmap.
/// Supported pixel depth: 1-, 4-, 8-, 16-, 24-, 32-bit per pixel for standard bitmap</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
public static FIBITMAP Allocate(int width, int height, int bpp)
{
return Allocate(width, height, bpp, 0, 0, 0);
}
/// <summary>
/// Creates a new bitmap in memory.
/// </summary>
/// <param name="type">Type of the image.</param>
/// <param name="width">Width of the new bitmap.</param>
/// <param name="height">Height of the new bitmap.</param>
/// <param name="bpp">Bit depth of the new Bitmap.
/// Supported pixel depth: 1-, 4-, 8-, 16-, 24-, 32-bit per pixel for standard bitmap</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
public static FIBITMAP AllocateT(FREE_IMAGE_TYPE type, int width, int height, int bpp)
{
return AllocateT(type, width, height, bpp, 0, 0, 0);
}
/// <summary>
/// Allocates a new image of the specified width, height and bit depth and optionally
/// fills it with the specified color. See remarks for further details.
/// </summary>
/// <param name="width">Width of the new bitmap.</param>
/// <param name="height">Height of the new bitmap.</param>
/// <param name="bpp">Bit depth of the new bitmap.
/// Supported pixel depth: 1-, 4-, 8-, 16-, 24-, 32-bit per pixel for standard bitmaps.</param>
/// <param name="color">The color to fill the bitmap with or <c>null</c>.</param>
/// <param name="options">Options to enable or disable function-features.</param>
/// <param name="palette">The palette of the bitmap or <c>null</c>.</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
/// <remarks>
/// This function is an extension to <see cref="Allocate"/>, which additionally supports
/// specifying a palette to be set for the newly create image, as well as specifying a
/// background color, the newly created image should initially be filled with.
/// <para/>
/// Basically, this function internally relies on function <see cref="Allocate"/>, followed by a
/// call to <see cref="FillBackground<T>"/>. This is why both parameters
/// <paramref name="color"/> and <paramref name="options"/> behave the same as it is
/// documented for function <see cref="FillBackground<T>"/>.
/// So, please refer to the documentation of <see cref="FillBackground<T>"/> to
/// learn more about parameters <paramref name="color"/> and <paramref name="options"/>.
/// <para/>
/// The palette specified through parameter <paramref name="palette"/> is only copied to the
/// newly created image, if the desired bit depth is smaller than or equal to 8 bits per pixel.
/// In other words, the <paramref name="palette"/> parameter is only taken into account for
/// palletized images. So, for an 8-bit image, the length is 256, for an 4-bit image it is 16
/// and it is 2 for a 1-bit image. In other words, this function does not support partial palettes.
/// <para/>
/// However, specifying a palette is not necesarily needed, even for palletized images. This
/// function is capable of implicitly creating a palette, if <paramref name="palette"/> is <c>null</c>.
/// If the specified background color is a greyscale value (red = green = blue) or if option
/// <see cref="FREE_IMAGE_COLOR_OPTIONS.FICO_ALPHA_IS_INDEX"/> is specified, a greyscale palette
/// is created. For a 1-bit image, only if the specified background color is either black or white,
/// a monochrome palette, consisting of black and white only is created. In any case, the darker
/// colors are stored at the smaller palette indices.
/// <para/>
/// If the specified background color is not a greyscale value, or is neither black nor white
/// for a 1-bit image, solely this specified color is injected into the otherwise black-initialized
/// palette. For this operation, option <see cref="FREE_IMAGE_COLOR_OPTIONS.FICO_ALPHA_IS_INDEX"/>
/// is implicit, so the specified <paramref name="color"/> is applied to the palette entry,
/// specified by the background color's <see cref="RGBQUAD.rgbReserved"/> field.
/// The image is then filled with this palette index.
/// <para/>
/// This function returns a newly created image as function <see cref="Allocate"/> does, if both
/// parameters <paramref name="color"/> and <paramref name="palette"/> are <c>null</c>.
/// If only <paramref name="color"/> is <c>null</c>, the palette pointed to by
/// parameter <paramref name="palette"/> is initially set for the new image, if a palletized
/// image of type <see cref="FREE_IMAGE_TYPE.FIT_BITMAP"/> is created.
/// However, in the latter case, this function returns an image, whose
/// pixels are all initialized with zeros so, the image will be filled with the color of the
/// first palette entry.
/// </remarks>
public static FIBITMAP AllocateEx(int width, int height, int bpp,
RGBQUAD? color, FREE_IMAGE_COLOR_OPTIONS options, RGBQUAD[] palette)
{
return AllocateEx(width, height, bpp, color, options, palette, 0, 0, 0);
}
/// <summary>
/// Allocates a new image of the specified width, height and bit depth and optionally
/// fills it with the specified color. See remarks for further details.
/// </summary>
/// <param name="width">Width of the new bitmap.</param>
/// <param name="height">Height of the new bitmap.</param>
/// <param name="bpp">Bit depth of the new bitmap.
/// Supported pixel depth: 1-, 4-, 8-, 16-, 24-, 32-bit per pixel for standard bitmaps.</param>
/// <param name="color">The color to fill the bitmap with or <c>null</c>.</param>
/// <param name="options">Options to enable or disable function-features.</param>
/// <param name="palette">The palette of the bitmap or <c>null</c>.</param>
/// <param name="red_mask">Red part of the color layout.
/// eg: 0xFF0000</param>
/// <param name="green_mask">Green part of the color layout.
/// eg: 0x00FF00</param>
/// <param name="blue_mask">Blue part of the color layout.
/// eg: 0x0000FF</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
/// <remarks>
/// This function is an extension to <see cref="Allocate"/>, which additionally supports
/// specifying a palette to be set for the newly create image, as well as specifying a
/// background color, the newly created image should initially be filled with.
/// <para/>
/// Basically, this function internally relies on function <see cref="Allocate"/>, followed by a
/// call to <see cref="FillBackground<T>"/>. This is why both parameters
/// <paramref name="color"/> and <paramref name="options"/> behave the same as it is
/// documented for function <see cref="FillBackground<T>"/>.
/// So, please refer to the documentation of <see cref="FillBackground<T>"/> to
/// learn more about parameters <paramref name="color"/> and <paramref name="options"/>.
/// <para/>
/// The palette specified through parameter <paramref name="palette"/> is only copied to the
/// newly created image, if the desired bit depth is smaller than or equal to 8 bits per pixel.
/// In other words, the <paramref name="palette"/> parameter is only taken into account for
/// palletized images. So, for an 8-bit image, the length is 256, for an 4-bit image it is 16
/// and it is 2 for a 1-bit image. In other words, this function does not support partial palettes.
/// <para/>
/// However, specifying a palette is not necesarily needed, even for palletized images. This
/// function is capable of implicitly creating a palette, if <paramref name="palette"/> is <c>null</c>.
/// If the specified background color is a greyscale value (red = green = blue) or if option
/// <see cref="FREE_IMAGE_COLOR_OPTIONS.FICO_ALPHA_IS_INDEX"/> is specified, a greyscale palette
/// is created. For a 1-bit image, only if the specified background color is either black or white,
/// a monochrome palette, consisting of black and white only is created. In any case, the darker
/// colors are stored at the smaller palette indices.
/// <para/>
/// If the specified background color is not a greyscale value, or is neither black nor white
/// for a 1-bit image, solely this specified color is injected into the otherwise black-initialized
/// palette. For this operation, option <see cref="FREE_IMAGE_COLOR_OPTIONS.FICO_ALPHA_IS_INDEX"/>
/// is implicit, so the specified <paramref name="color"/> is applied to the palette entry,
/// specified by the background color's <see cref="RGBQUAD.rgbReserved"/> field.
/// The image is then filled with this palette index.
/// <para/>
/// This function returns a newly created image as function <see cref="Allocate"/> does, if both
/// parameters <paramref name="color"/> and <paramref name="palette"/> are <c>null</c>.
/// If only <paramref name="color"/> is <c>null</c>, the palette pointed to by
/// parameter <paramref name="palette"/> is initially set for the new image, if a palletized
/// image of type <see cref="FREE_IMAGE_TYPE.FIT_BITMAP"/> is created.
/// However, in the latter case, this function returns an image, whose
/// pixels are all initialized with zeros so, the image will be filled with the color of the
/// first palette entry.
/// </remarks>
public static FIBITMAP AllocateEx(int width, int height, int bpp,
RGBQUAD? color, FREE_IMAGE_COLOR_OPTIONS options, RGBQUAD[] palette,
uint red_mask, uint green_mask, uint blue_mask)
{
if ((palette != null) && (bpp <= 8) && (palette.Length < (1 << bpp)))
return FIBITMAP.Zero;
if (color.HasValue)
{
GCHandle handle = new GCHandle();
try
{
RGBQUAD[] buffer = new RGBQUAD[] { color.Value };
handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
return AllocateEx(width, height, bpp, handle.AddrOfPinnedObject(),
options, palette, red_mask, green_mask, blue_mask);
}
finally
{
if (handle.IsAllocated)
handle.Free();
}
}
else
{
return AllocateEx(width, height, bpp, IntPtr.Zero,
options, palette, red_mask, green_mask, blue_mask);
}
}
/// <summary>
/// Allocates a new image of the specified type, width, height and bit depth and optionally
/// fills it with the specified color. See remarks for further details.
/// </summary>
/// <typeparam name="T">The type of the specified color.</typeparam>
/// <param name="type">Type of the image.</param>
/// <param name="width">Width of the new bitmap.</param>
/// <param name="height">Height of the new bitmap.</param>
/// <param name="bpp">Bit depth of the new bitmap.
/// Supported pixel depth: 1-, 4-, 8-, 16-, 24-, 32-bit per pixel for standard bitmap</param>
/// <param name="color">The color to fill the bitmap with or <c>null</c>.</param>
/// <param name="options">Options to enable or disable function-features.</param>
/// <param name="palette">The palette of the bitmap or <c>null</c>.</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
/// <remarks>
/// This function is an extension to <see cref="AllocateT"/>, which additionally supports
/// specifying a palette to be set for the newly create image, as well as specifying a
/// background color, the newly created image should initially be filled with.
/// <para/>
/// Basically, this function internally relies on function <see cref="AllocateT"/>, followed by a
/// call to <see cref="FillBackground<T>"/>. This is why both parameters
/// <paramref name="color"/> and <paramref name="options"/> behave the same as it is
/// documented for function <see cref="FillBackground<T>"/>. So, please refer to the
/// documentation of <see cref="FillBackground<T>"/> to learn more about parameters color and options.
/// <para/>
/// The palette specified through parameter palette is only copied to the newly created
/// image, if its image type is <see cref="FREE_IMAGE_TYPE.FIT_BITMAP"/> and the desired bit
/// depth is smaller than or equal to 8 bits per pixel. In other words, the <paramref name="palette"/>
/// palette is only taken into account for palletized images. However, if the preceding conditions
/// match and if <paramref name="palette"/> is not <c>null</c>, the palette is assumed to be at
/// least as large as the size of a fully populated palette for the desired bit depth.
/// So, for an 8-bit image, this length is 256, for an 4-bit image it is 16 and it is
/// 2 for a 1-bit image. In other words, this function does not support partial palettes.
/// <para/>
/// However, specifying a palette is not necesarily needed, even for palletized images. This
/// function is capable of implicitly creating a palette, if <paramref name="palette"/> is <c>null</c>.
/// If the specified background color is a greyscale value (red = green = blue) or if option
/// <see cref="FREE_IMAGE_COLOR_OPTIONS.FICO_ALPHA_IS_INDEX"/> is specified, a greyscale palette
/// is created. For a 1-bit image, only if the specified background color is either black or white,
/// a monochrome palette, consisting of black and white only is created. In any case, the darker
/// colors are stored at the smaller palette indices.
/// <para/>
/// If the specified background color is not a greyscale value, or is neither black nor white
/// for a 1-bit image, solely this specified color is injected into the otherwise black-initialized
/// palette. For this operation, option <see cref="FREE_IMAGE_COLOR_OPTIONS.FICO_ALPHA_IS_INDEX"/>
/// is implicit, so the specified color is applied to the palette entry, specified by the
/// background color's <see cref="RGBQUAD.rgbReserved"/> field. The image is then filled with
/// this palette index.
/// <para/>
/// This function returns a newly created image as function <see cref="AllocateT"/> does, if both
/// parameters <paramref name="color"/> and <paramref name="palette"/> are <c>null</c>.
/// If only <paramref name="color"/> is <c>null</c>, the palette pointed to by
/// parameter <paramref name="palette"/> is initially set for the new image, if a palletized
/// image of type <see cref="FREE_IMAGE_TYPE.FIT_BITMAP"/> is created.
/// However, in the latter case, this function returns an image, whose
/// pixels are all initialized with zeros so, the image will be filled with the color of the
/// first palette entry.
/// </remarks>
public static FIBITMAP AllocateExT<T>(FREE_IMAGE_TYPE type, int width, int height, int bpp,
T? color, FREE_IMAGE_COLOR_OPTIONS options, RGBQUAD[] palette) where T : struct
{
return AllocateExT(type, width, height, bpp, color, options, palette, 0, 0, 0);
}
/// <summary>
/// Allocates a new image of the specified type, width, height and bit depth and optionally
/// fills it with the specified color. See remarks for further details.
/// </summary>
/// <typeparam name="T">The type of the specified color.</typeparam>
/// <param name="type">Type of the image.</param>
/// <param name="width">Width of the new bitmap.</param>
/// <param name="height">Height of the new bitmap.</param>
/// <param name="bpp">Bit depth of the new bitmap.
/// Supported pixel depth: 1-, 4-, 8-, 16-, 24-, 32-bit per pixel for standard bitmap</param>
/// <param name="color">The color to fill the bitmap with or <c>null</c>.</param>
/// <param name="options">Options to enable or disable function-features.</param>
/// <param name="palette">The palette of the bitmap or <c>null</c>.</param>
/// <param name="red_mask">Red part of the color layout.
/// eg: 0xFF0000</param>
/// <param name="green_mask">Green part of the color layout.
/// eg: 0x00FF00</param>
/// <param name="blue_mask">Blue part of the color layout.
/// eg: 0x0000FF</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
/// <remarks>
/// This function is an extension to <see cref="AllocateT"/>, which additionally supports
/// specifying a palette to be set for the newly create image, as well as specifying a
/// background color, the newly created image should initially be filled with.
/// <para/>
/// Basically, this function internally relies on function <see cref="AllocateT"/>, followed by a
/// call to <see cref="FillBackground<T>"/>. This is why both parameters
/// <paramref name="color"/> and <paramref name="options"/> behave the same as it is
/// documented for function <see cref="FillBackground<T>"/>. So, please refer to the
/// documentation of <see cref="FillBackground<T>"/> to learn more about parameters color and options.
/// <para/>
/// The palette specified through parameter palette is only copied to the newly created
/// image, if its image type is <see cref="FREE_IMAGE_TYPE.FIT_BITMAP"/> and the desired bit
/// depth is smaller than or equal to 8 bits per pixel. In other words, the <paramref name="palette"/>
/// palette is only taken into account for palletized images. However, if the preceding conditions
/// match and if <paramref name="palette"/> is not <c>null</c>, the palette is assumed to be at
/// least as large as the size of a fully populated palette for the desired bit depth.
/// So, for an 8-bit image, this length is 256, for an 4-bit image it is 16 and it is
/// 2 for a 1-bit image. In other words, this function does not support partial palettes.
/// <para/>
/// However, specifying a palette is not necesarily needed, even for palletized images. This
/// function is capable of implicitly creating a palette, if <paramref name="palette"/> is <c>null</c>.
/// If the specified background color is a greyscale value (red = green = blue) or if option
/// <see cref="FREE_IMAGE_COLOR_OPTIONS.FICO_ALPHA_IS_INDEX"/> is specified, a greyscale palette
/// is created. For a 1-bit image, only if the specified background color is either black or white,
/// a monochrome palette, consisting of black and white only is created. In any case, the darker
/// colors are stored at the smaller palette indices.
/// <para/>
/// If the specified background color is not a greyscale value, or is neither black nor white
/// for a 1-bit image, solely this specified color is injected into the otherwise black-initialized
/// palette. For this operation, option <see cref="FREE_IMAGE_COLOR_OPTIONS.FICO_ALPHA_IS_INDEX"/>
/// is implicit, so the specified color is applied to the palette entry, specified by the
/// background color's <see cref="RGBQUAD.rgbReserved"/> field. The image is then filled with
/// this palette index.
/// <para/>
/// This function returns a newly created image as function <see cref="AllocateT"/> does, if both
/// parameters <paramref name="color"/> and <paramref name="palette"/> are <c>null</c>.
/// If only <paramref name="color"/> is <c>null</c>, the palette pointed to by
/// parameter <paramref name="palette"/> is initially set for the new image, if a palletized
/// image of type <see cref="FREE_IMAGE_TYPE.FIT_BITMAP"/> is created.
/// However, in the latter case, this function returns an image, whose
/// pixels are all initialized with zeros so, the image will be filled with the color of the
/// first palette entry.
/// </remarks>
public static FIBITMAP AllocateExT<T>(FREE_IMAGE_TYPE type, int width, int height, int bpp,
T? color, FREE_IMAGE_COLOR_OPTIONS options, RGBQUAD[] palette,
uint red_mask, uint green_mask, uint blue_mask) where T : struct
{
if ((palette != null) && (bpp <= 8) && (palette.Length < (1 << bpp)))
return FIBITMAP.Zero;
if (color.HasValue)
{
if (!CheckColorType(type, color.Value))
return FIBITMAP.Zero;
GCHandle handle = new GCHandle();
try
{
T[] buffer = new T[] { color.Value };
handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
return AllocateExT(type, width, height, bpp, handle.AddrOfPinnedObject(),
options, palette, red_mask, green_mask, blue_mask);
}
finally
{
if (handle.IsAllocated)
handle.Free();
}
}
else
{
return AllocateExT(type, width, height, bpp, IntPtr.Zero,
options, palette, red_mask, green_mask, blue_mask);
}
}
/// <summary>
/// Converts a FreeImage bitmap to a .NET <see cref="System.Drawing.Bitmap"/>.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <returns>The converted .NET <see cref="System.Drawing.Bitmap"/>.</returns>
/// <remarks>Copying metadata has been disabled until a proper way
/// of reading and storing metadata in a .NET bitmap is found.</remarks>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> is null.</exception>
/// <exception cref="ArgumentException">
/// The image type of <paramref name="dib"/> is not FIT_BITMAP.</exception>
public static Bitmap GetBitmap(FIBITMAP dib)
{
return GetBitmap(dib, true);
}
/// <summary>
/// Converts a FreeImage bitmap to a .NET <see cref="System.Drawing.Bitmap"/>.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <param name="copyMetadata">When true existing metadata will be copied.</param>
/// <returns>The converted .NET <see cref="System.Drawing.Bitmap"/>.</returns>
/// <remarks>Copying metadata has been disabled until a proper way
/// of reading and storing metadata in a .NET bitmap is found.</remarks>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> is null.</exception>
/// <exception cref="ArgumentException">
/// The image type of <paramref name="dib"/> is not FIT_BITMAP.</exception>
internal static Bitmap GetBitmap(FIBITMAP dib, bool copyMetadata)
{
if (dib.IsNull)
{
throw new ArgumentNullException("dib");
}
if (GetImageType(dib) != FREE_IMAGE_TYPE.FIT_BITMAP)
{
throw new ArgumentException("Only bitmaps with type of FIT_BITMAP can be converted.");
}
PixelFormat format = GetPixelFormat(dib);
if ((format == PixelFormat.Undefined) && (GetBPP(dib) == 16u))
{
throw new ArgumentException("Only 16bit 555 and 565 are supported.");
}
int height = (int)GetHeight(dib);
int width = (int)GetWidth(dib);
int pitch = (int)GetPitch(dib);
Bitmap result = new Bitmap(width, height, format);
BitmapData data;
// Locking the complete bitmap in writeonly mode
data = result.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, format);
// Writing the bitmap data directly into the new created .NET bitmap.
ConvertToRawBits(data.Scan0, dib, pitch, GetBPP(dib),
GetRedMask(dib), GetGreenMask(dib), GetBlueMask(dib), true);
// Unlock the bitmap
result.UnlockBits(data);
// Apply the bitmap resolution
if((GetResolutionX(dib) > 0) && (GetResolutionY(dib) > 0))
{
// SetResolution will throw an exception when zero values are given on input
result.SetResolution(GetResolutionX(dib), GetResolutionY(dib));
}
// Check whether the bitmap has a palette
if (GetPalette(dib) != IntPtr.Zero)
{
// Get the bitmaps palette to apply changes
ColorPalette palette = result.Palette;
// Get the orgininal palette
Color[] colorPalette = new Palette(dib).ColorData;
// Get the maximum number of palette entries to copy
int entriesToCopy = Math.Min(colorPalette.Length, palette.Entries.Length);
// Check whether the bitmap is transparent
if (IsTransparent(dib))
{
byte[] transTable = GetTransparencyTableEx(dib);
int i = 0;
int maxEntriesWithTrans = Math.Min(entriesToCopy, transTable.Length);
// Copy palette entries and include transparency
for (; i < maxEntriesWithTrans; i++)
{
palette.Entries[i] = Color.FromArgb(transTable[i], colorPalette[i]);
}
// Copy palette entries and that have no transparancy
for (; i < entriesToCopy; i++)
{
palette.Entries[i] = Color.FromArgb(0xFF, colorPalette[i]);
}
}
else
{
for (int i = 0; i < entriesToCopy; i++)
{
palette.Entries[i] = colorPalette[i];
}
}
// Set the bitmaps palette
result.Palette = palette;
}
// Copy metadata
if (copyMetadata)
{
try
{
List<PropertyItem> list = new List<PropertyItem>();
// Get a list of all types
FITAG tag;
FIMETADATA mData;
foreach (FREE_IMAGE_MDMODEL model in FREE_IMAGE_MDMODELS)
{
// Get a unique search handle
mData = FindFirstMetadata(model, dib, out tag);
// Check if metadata exists for this type
if (mData.IsNull) continue;
do
{
PropertyItem propItem = CreatePropertyItem();
propItem.Len = (int)GetTagLength(tag);
propItem.Id = (int)GetTagID(tag);
propItem.Type = (short)GetTagType(tag);
byte[] buffer = new byte[propItem.Len];
unsafe
{
byte* src = (byte*)GetTagValue(tag);
fixed (byte* dst = buffer)
{
CopyMemory(dst, src, (uint)propItem.Len);
}
}
propItem.Value = buffer;
list.Add(propItem);
}
while (FindNextMetadata(mData, out tag));
FindCloseMetadata(mData);
}
foreach (PropertyItem propItem in list)
{
result.SetPropertyItem(propItem);
}
}
catch
{
}
}
return result;
}
/// <summary>
/// Converts an .NET <see cref="System.Drawing.Bitmap"/> into a FreeImage bitmap.
/// </summary>
/// <param name="bitmap">The <see cref="System.Drawing.Bitmap"/> to convert.</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
/// <remarks>Copying metadata has been disabled until a proper way
/// of reading and storing metadata in a .NET bitmap is found.</remarks>
/// <exception cref="ArgumentNullException">
/// <paramref name="bitmap"/> is null.</exception>
/// <exception cref="ArgumentException">
/// The bitmaps pixelformat is invalid.</exception>
public static FIBITMAP CreateFromBitmap(Bitmap bitmap)
{
return CreateFromBitmap(bitmap, false);
}
/// <summary>
/// Converts an .NET <see cref="System.Drawing.Bitmap"/> into a FreeImage bitmap.
/// </summary>
/// <param name="bitmap">The <see cref="System.Drawing.Bitmap"/> to convert.</param>
/// <param name="copyMetadata">When true existing metadata will be copied.</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
/// <remarks>Copying metadata has been disabled until a proper way
/// of reading and storing metadata in a .NET bitmap is found.</remarks>
/// <exception cref="ArgumentNullException">
/// <paramref name="bitmap"/> is null.</exception>
/// <exception cref="ArgumentException">
/// The bitmaps pixelformat is invalid.</exception>
internal static FIBITMAP CreateFromBitmap(Bitmap bitmap, bool copyMetadata)
{
if (bitmap == null)
{
throw new ArgumentNullException("bitmap");
}
uint bpp, red_mask, green_mask, blue_mask;
FREE_IMAGE_TYPE type;
if (!GetFormatParameters(bitmap.PixelFormat, out type, out bpp, out red_mask, out green_mask, out blue_mask))
{
throw new ArgumentException("The bitmaps pixelformat is invalid.");
}
// Locking the complete bitmap in readonly mode
BitmapData data = bitmap.LockBits(
new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, bitmap.PixelFormat);
// Copying the bitmap data directly from the .NET bitmap
FIBITMAP result = ConvertFromRawBits(
data.Scan0,
type,
data.Width,
data.Height,
data.Stride,
bpp,
red_mask,
green_mask,
blue_mask,
true);
bitmap.UnlockBits(data);
// Handle palette
if (GetPalette(result) != IntPtr.Zero)
{
Palette palette = new Palette(result);
Color[] colors = bitmap.Palette.Entries;
// Only copy available palette entries
int entriesToCopy = Math.Min(palette.Length, colors.Length);
byte[] transTable = new byte[entriesToCopy];
for (int i = 0; i < entriesToCopy; i++)
{
RGBQUAD color = (RGBQUAD)colors[i];
color.rgbReserved = 0x00;
palette[i] = color;
transTable[i] = colors[i].A;
}
if ((bitmap.Flags & (int)ImageFlags.HasAlpha) != 0)
{
FreeImage.SetTransparencyTable(result, transTable);
}
}
// Handle meta data
// Disabled
//if (copyMetadata)
//{
// foreach (PropertyItem propItem in bitmap.PropertyItems)
// {
// FITAG tag = CreateTag();
// SetTagLength(tag, (uint)propItem.Len);
// SetTagID(tag, (ushort)propItem.Id);
// SetTagType(tag, (FREE_IMAGE_MDTYPE)propItem.Type);
// SetTagValue(tag, propItem.Value);
// SetMetadata(FREE_IMAGE_MDMODEL.FIMD_EXIF_EXIF, result, "", tag);
// }
//}
return result;
}
/// <summary>
/// Converts a raw bitmap to a FreeImage bitmap.
/// </summary>
/// <param name="bits">Array of bytes containing the raw bitmap.</param>
/// <param name="type">The type of the raw bitmap.</param>
/// <param name="width">The width in pixels of the raw bitmap.</param>
/// <param name="height">The height in pixels of the raw bitmap.</param>
/// <param name="pitch">Defines the total width of a scanline in the raw bitmap,
/// including padding bytes.</param>
/// <param name="bpp">The bit depth (bits per pixel) of the raw bitmap.</param>
/// <param name="red_mask">The bit mask describing the bits used to store a single
/// pixel's red component in the raw bitmap. This is only applied to 16-bpp raw bitmaps.</param>
/// <param name="green_mask">The bit mask describing the bits used to store a single
/// pixel's green component in the raw bitmap. This is only applied to 16-bpp raw bitmaps.</param>
/// <param name="blue_mask">The bit mask describing the bits used to store a single
/// pixel's blue component in the raw bitmap. This is only applied to 16-bpp raw bitmaps.</param>
/// <param name="topdown">If true, the raw bitmap is stored in top-down order (top-left pixel first)
/// and in bottom-up order (bottom-left pixel first) otherwise.</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
public static unsafe FIBITMAP ConvertFromRawBits(
byte[] bits,
FREE_IMAGE_TYPE type,
int width,
int height,
int pitch,
uint bpp,
uint red_mask,
uint green_mask,
uint blue_mask,
bool topdown)
{
fixed (byte* ptr = bits)
{
return ConvertFromRawBits(
(IntPtr)ptr,
type,
width,
height,
pitch,
bpp,
red_mask,
green_mask,
blue_mask,
topdown);
}
}
/// <summary>
/// Converts a raw bitmap to a FreeImage bitmap.
/// </summary>
/// <param name="bits">Pointer to the memory block containing the raw bitmap.</param>
/// <param name="type">The type of the raw bitmap.</param>
/// <param name="width">The width in pixels of the raw bitmap.</param>
/// <param name="height">The height in pixels of the raw bitmap.</param>
/// <param name="pitch">Defines the total width of a scanline in the raw bitmap,
/// including padding bytes.</param>
/// <param name="bpp">The bit depth (bits per pixel) of the raw bitmap.</param>
/// <param name="red_mask">The bit mask describing the bits used to store a single
/// pixel's red component in the raw bitmap. This is only applied to 16-bpp raw bitmaps.</param>
/// <param name="green_mask">The bit mask describing the bits used to store a single
/// pixel's green component in the raw bitmap. This is only applied to 16-bpp raw bitmaps.</param>
/// <param name="blue_mask">The bit mask describing the bits used to store a single
/// pixel's blue component in the raw bitmap. This is only applied to 16-bpp raw bitmaps.</param>
/// <param name="topdown">If true, the raw bitmap is stored in top-down order (top-left pixel first)
/// and in bottom-up order (bottom-left pixel first) otherwise.</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
public static unsafe FIBITMAP ConvertFromRawBits(
IntPtr bits,
FREE_IMAGE_TYPE type,
int width,
int height,
int pitch,
uint bpp,
uint red_mask,
uint green_mask,
uint blue_mask,
bool topdown)
{
byte* addr = (byte*)bits;
if ((addr == null) || (width <= 0) || (height <= 0))
{
return FIBITMAP.Zero;
}
FIBITMAP dib = AllocateT(type, width, height, (int)bpp, red_mask, green_mask, blue_mask);
if (dib != FIBITMAP.Zero)
{
if (topdown)
{
for (int i = height - 1; i >= 0; --i)
{
CopyMemory((byte*)GetScanLine(dib, i), addr, (int)GetLine(dib));
addr += pitch;
}
}
else
{
for (int i = 0; i < height; ++i)
{
CopyMemory((byte*)GetScanLine(dib, i), addr, (int)GetLine(dib));
addr += pitch;
}
}
}
return dib;
}
/// <summary>
/// Saves a .NET <see cref="System.Drawing.Bitmap"/> to a file.
/// </summary>
/// <param name="bitmap">The .NET <see cref="System.Drawing.Bitmap"/> to save.</param>
/// <param name="filename">Name of the file to save to.</param>
/// <returns>Returns true on success, false on failure.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="bitmap"/> or <paramref name="filename"/> is null.</exception>
/// <exception cref="ArgumentException">
/// The bitmaps pixelformat is invalid.</exception>
public static bool SaveBitmap(Bitmap bitmap, string filename)
{
return SaveBitmap(
bitmap,
filename,
FREE_IMAGE_FORMAT.FIF_UNKNOWN,
FREE_IMAGE_SAVE_FLAGS.DEFAULT);
}
/// <summary>
/// Saves a .NET <see cref="System.Drawing.Bitmap"/> to a file.
/// </summary>
/// <param name="bitmap">The .NET <see cref="System.Drawing.Bitmap"/> to save.</param>
/// <param name="filename">Name of the file to save to.</param>
/// <param name="flags">Flags to enable or disable plugin-features.</param>
/// <returns>Returns true on success, false on failure.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="bitmap"/> or <paramref name="filename"/> is null.</exception>
/// <exception cref="ArgumentException">
/// The bitmaps pixelformat is invalid.</exception>
public static bool SaveBitmap(Bitmap bitmap, string filename, FREE_IMAGE_SAVE_FLAGS flags)
{
return SaveBitmap(
bitmap,
filename,
FREE_IMAGE_FORMAT.FIF_UNKNOWN,
flags);
}
/// <summary>
/// Saves a .NET <see cref="System.Drawing.Bitmap"/> to a file.
/// </summary>
/// <param name="bitmap">The .NET <see cref="System.Drawing.Bitmap"/> to save.</param>
/// <param name="filename">Name of the file to save to.</param>
/// <param name="format">Format of the bitmap. If the format should be taken from the
/// filename use <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/>.</param>
/// <param name="flags">Flags to enable or disable plugin-features.</param>
/// <returns>Returns true on success, false on failure.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="bitmap"/> or <paramref name="filename"/> is null.</exception>
/// <exception cref="ArgumentException">
/// The bitmaps pixelformat is invalid.</exception>
public static bool SaveBitmap(
Bitmap bitmap,
string filename,
FREE_IMAGE_FORMAT format,
FREE_IMAGE_SAVE_FLAGS flags)
{
FIBITMAP dib = CreateFromBitmap(bitmap);
bool result = SaveEx(dib, filename, format, flags);
Unload(dib);
return result;
}
/// <summary>
/// Loads a FreeImage bitmap.
/// The file will be loaded with default loading flags.
/// </summary>
/// <param name="filename">The complete name of the file to load.</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
/// <exception cref="FileNotFoundException">
/// <paramref name="filename"/> does not exists.</exception>
public static FIBITMAP LoadEx(string filename)
{
FREE_IMAGE_FORMAT format = FREE_IMAGE_FORMAT.FIF_UNKNOWN;
return LoadEx(filename, FREE_IMAGE_LOAD_FLAGS.DEFAULT, ref format);
}
/// <summary>
/// Loads a FreeImage bitmap.
/// Load flags can be provided by the flags parameter.
/// </summary>
/// <param name="filename">The complete name of the file to load.</param>
/// <param name="flags">Flags to enable or disable plugin-features.</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
/// <exception cref="FileNotFoundException">
/// <paramref name="filename"/> does not exists.</exception>
public static FIBITMAP LoadEx(string filename, FREE_IMAGE_LOAD_FLAGS flags)
{
FREE_IMAGE_FORMAT format = FREE_IMAGE_FORMAT.FIF_UNKNOWN;
return LoadEx(filename, flags, ref format);
}
/// <summary>
/// Loads a FreeImage bitmap.
/// In case the loading format is <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/> the files
/// real format is being analysed. If no plugin can read the file, format remains
/// <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/> and 0 is returned.
/// The file will be loaded with default loading flags.
/// </summary>
/// <param name="filename">The complete name of the file to load.</param>
/// <param name="format">Format of the image. If the format is unknown use
/// <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/>.
/// In case a suitable format was found by LoadEx it will be returned in format.</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
/// <exception cref="FileNotFoundException">
/// <paramref name="filename"/> does not exists.</exception>
public static FIBITMAP LoadEx(string filename, ref FREE_IMAGE_FORMAT format)
{
return LoadEx(filename, FREE_IMAGE_LOAD_FLAGS.DEFAULT, ref format);
}
/// <summary>
/// Loads a FreeImage bitmap.
/// In case the loading format is <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/> the files
/// real format is being analysed. If no plugin can read the file, format remains
/// <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/> and 0 is returned.
/// Load flags can be provided by the flags parameter.
/// </summary>
/// <param name="filename">The complete name of the file to load.</param>
/// <param name="flags">Flags to enable or disable plugin-features.</param>
/// <param name="format">Format of the image. If the format is unknown use
/// <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/>.
/// In case a suitable format was found by LoadEx it will be returned in format.
/// </param>
/// <returns>Handle to a FreeImage bitmap.</returns>
/// <exception cref="FileNotFoundException">
/// <paramref name="filename"/> does not exists.</exception>
public static FIBITMAP LoadEx(string filename, FREE_IMAGE_LOAD_FLAGS flags, ref FREE_IMAGE_FORMAT format)
{
// check if file exists
if (!File.Exists(filename))
{
throw new FileNotFoundException(filename + " could not be found.");
}
FIBITMAP dib = new FIBITMAP();
if (format == FREE_IMAGE_FORMAT.FIF_UNKNOWN)
{
// query all plugins to see if one can read the file
format = GetFileType(filename, 0);
}
// check if the plugin is capable of loading files
if (FIFSupportsReading(format))
{
dib = Load(format, filename, flags);
}
return dib;
}
/// <summary>
/// Loads a .NET <see cref="System.Drawing.Bitmap"/> from a file.
/// </summary>
/// <param name="filename">Name of the file to be loaded.</param>
/// <param name="format">Format of the image. If the format should be taken from the
/// filename use <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/>.</param>
/// <param name="flags">Flags to enable or disable plugin-features.</param>
/// <returns>The loaded .NET <see cref="System.Drawing.Bitmap"/>.</returns>
/// <exception cref="FileNotFoundException">
/// <paramref name="filename"/> does not exists.</exception>
/// <exception cref="ArgumentException">
/// The image type of the image is not <see cref="FREE_IMAGE_TYPE.FIT_BITMAP"/>.</exception>
public static Bitmap LoadBitmap(string filename, FREE_IMAGE_LOAD_FLAGS flags, ref FREE_IMAGE_FORMAT format)
{
FIBITMAP dib = LoadEx(filename, flags, ref format);
Bitmap result = GetBitmap(dib, true);
Unload(dib);
return result;
}
/// <summary>
/// Deletes a previously loaded FreeImage bitmap from memory and resets the handle to 0.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
public static void UnloadEx(ref FIBITMAP dib)
{
if (!dib.IsNull)
{
Unload(dib);
dib.SetNull();
}
}
/// <summary>
/// Saves a previously loaded FreeImage bitmap to a file.
/// The format is taken off the filename.
/// If no suitable format was found false will be returned.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <param name="filename">The complete name of the file to save to.
/// The extension will be corrected if it is no valid extension for the
/// selected format or if no extension was specified.</param>
/// <returns>Returns true on success, false on failure.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> or <paramref name="filename"/> is null.</exception>
public static bool SaveEx(FIBITMAP dib, string filename)
{
return SaveEx(
ref dib,
filename,
FREE_IMAGE_FORMAT.FIF_UNKNOWN,
FREE_IMAGE_SAVE_FLAGS.DEFAULT,
FREE_IMAGE_COLOR_DEPTH.FICD_AUTO,
false);
}
/// <summary>
/// Saves a previously loaded FreeImage bitmap to a file.
/// In case the loading format is <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/>
/// the format is taken off the filename.
/// If no suitable format was found false will be returned.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <param name="filename">The complete name of the file to save to.
/// The extension will be corrected if it is no valid extension for the
/// selected format or if no extension was specified.</param>
/// <param name="format">Format of the image. If the format should be taken from the
/// filename use <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/>.</param>
/// <returns>Returns true on success, false on failure.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> or <paramref name="filename"/> is null.</exception>
public static bool SaveEx(
FIBITMAP dib,
string filename,
FREE_IMAGE_FORMAT format)
{
return SaveEx(
ref dib,
filename,
format,
FREE_IMAGE_SAVE_FLAGS.DEFAULT,
FREE_IMAGE_COLOR_DEPTH.FICD_AUTO,
false);
}
/// <summary>
/// Saves a previously loaded FreeImage bitmap to a file.
/// The format is taken off the filename.
/// If no suitable format was found false will be returned.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <param name="filename">The complete name of the file to save to.
/// The extension will be corrected if it is no valid extension for the
/// selected format or if no extension was specified.</param>
/// <param name="unloadSource">When true the structure will be unloaded on success.
/// If the function failed and returned false, the bitmap was not unloaded.</param>
/// <returns>Returns true on success, false on failure.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> or <paramref name="filename"/> is null.</exception>
public static bool SaveEx(
ref FIBITMAP dib,
string filename,
bool unloadSource)
{
return SaveEx(
ref dib,
filename,
FREE_IMAGE_FORMAT.FIF_UNKNOWN,
FREE_IMAGE_SAVE_FLAGS.DEFAULT,
FREE_IMAGE_COLOR_DEPTH.FICD_AUTO,
unloadSource);
}
/// <summary>
/// Saves a previously loaded FreeImage bitmap to a file.
/// The format is taken off the filename.
/// If no suitable format was found false will be returned.
/// Save flags can be provided by the flags parameter.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <param name="filename">The complete name of the file to save to.
/// The extension will be corrected if it is no valid extension for the
/// selected format or if no extension was specified</param>
/// <param name="flags">Flags to enable or disable plugin-features.</param>
/// <returns>Returns true on success, false on failure.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> or <paramref name="filename"/> is null.</exception>
public static bool SaveEx(
FIBITMAP dib,
string filename,
FREE_IMAGE_SAVE_FLAGS flags)
{
return SaveEx(
ref dib,
filename,
FREE_IMAGE_FORMAT.FIF_UNKNOWN,
flags,
FREE_IMAGE_COLOR_DEPTH.FICD_AUTO,
false);
}
/// <summary>
/// Saves a previously loaded FreeImage bitmap to a file.
/// The format is taken off the filename.
/// If no suitable format was found false will be returned.
/// Save flags can be provided by the flags parameter.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <param name="filename">The complete name of the file to save to.
/// The extension will be corrected if it is no valid extension for the
/// selected format or if no extension was specified.</param>
/// <param name="flags">Flags to enable or disable plugin-features.</param>
/// <param name="unloadSource">When true the structure will be unloaded on success.
/// If the function failed and returned false, the bitmap was not unloaded.</param>
/// <returns>Returns true on success, false on failure.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> or <paramref name="filename"/> is null.</exception>
public static bool SaveEx(
ref FIBITMAP dib,
string filename,
FREE_IMAGE_SAVE_FLAGS flags,
bool unloadSource)
{
return SaveEx(
ref dib,
filename,
FREE_IMAGE_FORMAT.FIF_UNKNOWN,
flags,
FREE_IMAGE_COLOR_DEPTH.FICD_AUTO,
unloadSource);
}
/// <summary>
/// Saves a previously loaded FreeImage bitmap to a file.
/// In case the loading format is <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/>
/// the format is taken off the filename.
/// If no suitable format was found false will be returned.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <param name="filename">The complete name of the file to save to.
/// The extension will be corrected if it is no valid extension for the
/// selected format or if no extension was specified.</param>
/// <param name="format">Format of the image. If the format should be taken from the
/// filename use <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/>.</param>
/// <param name="unloadSource">When true the structure will be unloaded on success.
/// If the function failed and returned false, the bitmap was not unloaded.</param>
/// <returns>Returns true on success, false on failure.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> or <paramref name="filename"/> is null.</exception>
public static bool SaveEx(
ref FIBITMAP dib,
string filename,
FREE_IMAGE_FORMAT format,
bool unloadSource)
{
return SaveEx(
ref dib,
filename,
format,
FREE_IMAGE_SAVE_FLAGS.DEFAULT,
FREE_IMAGE_COLOR_DEPTH.FICD_AUTO,
unloadSource);
}
/// <summary>
/// Saves a previously loaded FreeImage bitmap to a file.
/// In case the loading format is <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/>
/// the format is taken off the filename.
/// If no suitable format was found false will be returned.
/// Save flags can be provided by the flags parameter.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <param name="filename">The complete name of the file to save to.
/// The extension will be corrected if it is no valid extension for the
/// selected format or if no extension was specified.</param>
/// <param name="format">Format of the image. If the format should be taken from the
/// filename use <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/>.</param>
/// <param name="flags">Flags to enable or disable plugin-features.</param>
/// <returns>Returns true on success, false on failure.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> or <paramref name="filename"/> is null.</exception>
public static bool SaveEx(
FIBITMAP dib,
string filename,
FREE_IMAGE_FORMAT format,
FREE_IMAGE_SAVE_FLAGS flags)
{
return SaveEx(
ref dib,
filename,
format,
flags,
FREE_IMAGE_COLOR_DEPTH.FICD_AUTO,
false);
}
/// <summary>
/// Saves a previously loaded FreeImage bitmap to a file.
/// In case the loading format is <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/>
/// the format is taken off the filename.
/// If no suitable format was found false will be returned.
/// Save flags can be provided by the flags parameter.
/// The bitmaps color depth can be set by 'colorDepth'.
/// If set to <see cref="FREE_IMAGE_COLOR_DEPTH.FICD_AUTO"/> a suitable color depth
/// will be taken if available.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <param name="filename">The complete name of the file to save to.
/// The extension will be corrected if it is no valid extension for the
/// selected format or if no extension was specified.</param>
/// <param name="format">Format of the image. If the format should be taken from the
/// filename use <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/>.</param>
/// <param name="flags">Flags to enable or disable plugin-features.</param>
/// <param name="colorDepth">The new color depth of the bitmap.
/// Set to <see cref="FREE_IMAGE_COLOR_DEPTH.FICD_AUTO"/> if Save should take the
/// best suitable color depth.
/// If a color depth is selected that the provided format cannot write an
/// error-message will be thrown.</param>
/// <param name="unloadSource">When true the structure will be unloaded on success.
/// If the function failed and returned false, the bitmap was not unloaded.</param>
/// <returns>Returns true on success, false on failure.</returns>
/// <exception cref="ArgumentException">
/// A direct color conversion failed.</exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> or <paramref name="filename"/> is null.</exception>
public static bool SaveEx(
ref FIBITMAP dib,
string filename,
FREE_IMAGE_FORMAT format,
FREE_IMAGE_SAVE_FLAGS flags,
FREE_IMAGE_COLOR_DEPTH colorDepth,
bool unloadSource)
{
if (dib.IsNull)
{
throw new ArgumentNullException("dib");
}
if (filename == null)
{
throw new ArgumentNullException("filename");
}
bool result = false;
// Gets format from filename if the format is unknown
if (format == FREE_IMAGE_FORMAT.FIF_UNKNOWN)
{
format = GetFIFFromFilename(filename);
}
if (format != FREE_IMAGE_FORMAT.FIF_UNKNOWN)
{
// Checks writing support
if (FIFSupportsWriting(format) && FIFSupportsExportType(format, GetImageType(dib)))
{
// Check valid filename and correct it if needed
if (!IsFilenameValidForFIF(format, filename))
{
string extension = GetPrimaryExtensionFromFIF(format);
filename = Path.ChangeExtension(filename, extension);
}
FIBITMAP dibToSave = PrepareBitmapColorDepth(dib, format, colorDepth);
try
{
result = Save(format, dibToSave, filename, flags);
}
finally
{
// Always unload a temporary created bitmap.
if (dibToSave != dib)
{
UnloadEx(ref dibToSave);
}
// On success unload the bitmap
if (result && unloadSource)
{
UnloadEx(ref dib);
}
}
}
}
return result;
}
/// <summary>
/// Loads a FreeImage bitmap.
/// The stream must be set to the correct position before calling LoadFromStream.
/// </summary>
/// <param name="stream">The stream to read from.</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="stream"/> is null.</exception>
/// <exception cref="ArgumentException">
/// <paramref name="stream"/> is not capable of reading.</exception>
public static FIBITMAP LoadFromStream(Stream stream)
{
FREE_IMAGE_FORMAT format = FREE_IMAGE_FORMAT.FIF_UNKNOWN;
return LoadFromStream(stream, FREE_IMAGE_LOAD_FLAGS.DEFAULT, ref format);
}
/// <summary>
/// Loads a FreeImage bitmap.
/// The stream must be set to the correct position before calling LoadFromStream.
/// </summary>
/// <param name="stream">The stream to read from.</param>
/// <param name="flags">Flags to enable or disable plugin-features.</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="stream"/> is null.</exception>
/// <exception cref="ArgumentException">
/// <paramref name="stream"/> is not capable of reading.</exception>
public static FIBITMAP LoadFromStream(Stream stream, FREE_IMAGE_LOAD_FLAGS flags)
{
FREE_IMAGE_FORMAT format = FREE_IMAGE_FORMAT.FIF_UNKNOWN;
return LoadFromStream(stream, flags, ref format);
}
/// <summary>
/// Loads a FreeImage bitmap.
/// In case the loading format is <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/> the
/// bitmaps real format is being analysed.
/// The stream must be set to the correct position before calling LoadFromStream.
/// </summary>
/// <param name="stream">The stream to read from.</param>
/// <param name="format">Format of the image. If the format is unknown use
/// <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/>.
/// In case a suitable format was found by LoadFromStream it will be returned in format.</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="stream"/> is null.</exception>
/// <exception cref="ArgumentException">
/// <paramref name="stream"/> is not capable of reading.</exception>
public static FIBITMAP LoadFromStream(Stream stream, ref FREE_IMAGE_FORMAT format)
{
return LoadFromStream(stream, FREE_IMAGE_LOAD_FLAGS.DEFAULT, ref format);
}
/// <summary>
/// Loads a FreeImage bitmap.
/// In case the loading format is <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/>
/// the bitmaps real format is being analysed.
/// The stream must be set to the correct position before calling LoadFromStream.
/// </summary>
/// <param name="stream">The stream to read from.</param>
/// <param name="flags">Flags to enable or disable plugin-features.</param>
/// <param name="format">Format of the image. If the format is unknown use
/// <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/>.
/// In case a suitable format was found by LoadFromStream it will be returned in format.</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="stream"/> is null.</exception>
/// <exception cref="ArgumentException">
/// <paramref name="stream"/> is not capable of reading.</exception>
public static FIBITMAP LoadFromStream(
Stream stream,
FREE_IMAGE_LOAD_FLAGS flags,
ref FREE_IMAGE_FORMAT format)
{
if (stream == null)
{
throw new ArgumentNullException("stream");
}
if (!stream.CanRead)
{
throw new ArgumentException("stream is not capable of reading.");
}
// Wrap the source stream if it is unable to seek (which is required by FreeImage)
stream = (stream.CanSeek) ? stream : new StreamWrapper(stream, true);
stream.Position = 0L;
if (format == FREE_IMAGE_FORMAT.FIF_UNKNOWN)
{
// Get the format of the bitmap
format = GetFileTypeFromStream(stream);
// Restore the streams position
stream.Position = 0L;
}
if (!FIFSupportsReading(format))
{
return FIBITMAP.Zero;
}
// Create a 'FreeImageIO' structure for calling 'LoadFromHandle'
// using the internal structure 'FreeImageStreamIO'.
FreeImageIO io = FreeImageStreamIO.io;
using (fi_handle handle = new fi_handle(stream))
{
return LoadFromHandle(format, ref io, handle, flags);
}
}
/// <summary>
/// Saves a previously loaded FreeImage bitmap to a stream.
/// The stream must be set to the correct position before calling SaveToStream.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <param name="stream">The stream to write to.</param>
/// <param name="format">Format of the image.</param>
/// <returns>Returns true on success, false on failure.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> or <paramref name="stream"/> is null.</exception>
/// <exception cref="ArgumentException">
/// <paramref name="stream"/> cannot write.</exception>
public static bool SaveToStream(
FIBITMAP dib,
Stream stream,
FREE_IMAGE_FORMAT format)
{
return SaveToStream(
ref dib,
stream,
format,
FREE_IMAGE_SAVE_FLAGS.DEFAULT,
FREE_IMAGE_COLOR_DEPTH.FICD_AUTO,
false);
}
/// <summary>
/// Saves a previously loaded FreeImage bitmap to a stream.
/// The stream must be set to the correct position before calling SaveToStream.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <param name="stream">The stream to write to.</param>
/// <param name="format">Format of the image.</param>
/// <param name="unloadSource">When true the structure will be unloaded on success.</param>
/// <returns>Returns true on success, false on failure.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> or <paramref name="stream"/> is null.</exception>
/// <exception cref="ArgumentException">
/// <paramref name="stream"/> cannot write.</exception>
public static bool SaveToStream(
ref FIBITMAP dib,
Stream stream,
FREE_IMAGE_FORMAT format,
bool unloadSource)
{
return SaveToStream(
ref dib,
stream,
format,
FREE_IMAGE_SAVE_FLAGS.DEFAULT,
FREE_IMAGE_COLOR_DEPTH.FICD_AUTO,
unloadSource);
}
/// <summary>
/// Saves a previously loaded FreeImage bitmap to a stream.
/// The stream must be set to the correct position before calling SaveToStream.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <param name="stream">The stream to write to.</param>
/// <param name="format">Format of the image.</param>
/// <param name="flags">Flags to enable or disable plugin-features.</param>
/// <returns>Returns true on success, false on failure.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> or <paramref name="stream"/> is null.</exception>
/// <exception cref="ArgumentException">
/// <paramref name="stream"/> cannot write.</exception>
public static bool SaveToStream(
FIBITMAP dib,
Stream stream,
FREE_IMAGE_FORMAT format,
FREE_IMAGE_SAVE_FLAGS flags)
{
return SaveToStream(
ref dib,
stream,
format,
flags,
FREE_IMAGE_COLOR_DEPTH.FICD_AUTO,
false);
}
/// <summary>
/// Saves a previously loaded FreeImage bitmap to a stream.
/// The stream must be set to the correct position before calling SaveToStream.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <param name="stream">The stream to write to.</param>
/// <param name="format">Format of the image.</param>
/// <param name="flags">Flags to enable or disable plugin-features.</param>
/// <param name="unloadSource">When true the structure will be unloaded on success.</param>
/// <returns>Returns true on success, false on failure.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> or <paramref name="stream"/> is null.</exception>
/// <exception cref="ArgumentException">
/// <paramref name="stream"/> cannot write.</exception>
public static bool SaveToStream(
ref FIBITMAP dib,
Stream stream,
FREE_IMAGE_FORMAT format,
FREE_IMAGE_SAVE_FLAGS flags,
bool unloadSource)
{
return SaveToStream(
ref dib, stream,
format,
flags,
FREE_IMAGE_COLOR_DEPTH.FICD_AUTO,
unloadSource);
}
/// <summary>
/// Saves a previously loaded FreeImage bitmap to a stream.
/// The stream must be set to the correct position before calling SaveToStream.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <param name="stream">The stream to write to.</param>
/// <param name="format">Format of the image.</param>
/// <param name="flags">Flags to enable or disable plugin-features.</param>
/// <param name="colorDepth">The new color depth of the bitmap.
/// Set to <see cref="FREE_IMAGE_COLOR_DEPTH.FICD_AUTO"/> if SaveToStream should
/// take the best suitable color depth.
/// If a color depth is selected that the provided format cannot write an
/// error-message will be thrown.</param>
/// <returns>Returns true on success, false on failure.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> or <paramref name="stream"/> is null.</exception>
/// <exception cref="ArgumentException">
/// <paramref name="stream"/> cannot write.</exception>
public static bool SaveToStream(
FIBITMAP dib,
Stream stream,
FREE_IMAGE_FORMAT format,
FREE_IMAGE_SAVE_FLAGS flags,
FREE_IMAGE_COLOR_DEPTH colorDepth)
{
return SaveToStream(
ref dib,
stream,
format,
flags,
colorDepth,
false);
}
/// <summary>
/// Saves a previously loaded FreeImage bitmap to a stream.
/// The stream must be set to the correct position before calling SaveToStream.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <param name="stream">The stream to write to.</param>
/// <param name="format">Format of the image.</param>
/// <param name="flags">Flags to enable or disable plugin-features.</param>
/// <param name="colorDepth">The new color depth of the bitmap.
/// Set to <see cref="FREE_IMAGE_COLOR_DEPTH.FICD_AUTO"/> if SaveToStream should
/// take the best suitable color depth.
/// If a color depth is selected that the provided format cannot write an
/// error-message will be thrown.</param>
/// <param name="unloadSource">When true the structure will be unloaded on success.</param>
/// <returns>Returns true on success, false on failure.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> or <paramref name="stream"/> is null.</exception>
/// <exception cref="ArgumentException">
/// <paramref name="stream"/> cannot write.</exception>
public static bool SaveToStream(
ref FIBITMAP dib,
Stream stream,
FREE_IMAGE_FORMAT format,
FREE_IMAGE_SAVE_FLAGS flags,
FREE_IMAGE_COLOR_DEPTH colorDepth,
bool unloadSource)
{
if (dib.IsNull)
{
throw new ArgumentNullException("dib");
}
if (stream == null)
{
throw new ArgumentNullException("stream");
}
if (!stream.CanWrite)
{
throw new ArgumentException("stream is not capable of writing.");
}
if ((!FIFSupportsWriting(format)) || (!FIFSupportsExportType(format, GetImageType(dib))))
{
return false;
}
FIBITMAP dibToSave = PrepareBitmapColorDepth(dib, format, colorDepth);
bool result = false;
try
{
// Create a 'FreeImageIO' structure for calling 'SaveToHandle'
FreeImageIO io = FreeImageStreamIO.io;
using (fi_handle handle = new fi_handle(stream))
{
result = SaveToHandle(format, dibToSave, ref io, handle, flags);
}
}
finally
{
// Always unload a temporary created bitmap.
if (dibToSave != dib)
{
UnloadEx(ref dibToSave);
}
// On success unload the bitmap
if (result && unloadSource)
{
UnloadEx(ref dib);
}
}
return result;
}
#endregion
#region Plugin functions
/// <summary>
/// Checks if an extension is valid for a certain format.
/// </summary>
/// <param name="fif">The desired format.</param>
/// <param name="extension">The desired extension.</param>
/// <returns>True if the extension is valid for the given format, false otherwise.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="extension"/> is null.</exception>
public static bool IsExtensionValidForFIF(FREE_IMAGE_FORMAT fif, string extension)
{
return IsExtensionValidForFIF(fif, extension, StringComparison.CurrentCultureIgnoreCase);
}
/// <summary>
/// Checks if an extension is valid for a certain format.
/// </summary>
/// <param name="fif">The desired format.</param>
/// <param name="extension">The desired extension.</param>
/// <param name="comparisonType">The string comparison type.</param>
/// <returns>True if the extension is valid for the given format, false otherwise.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="extension"/> is null.</exception>
public static bool IsExtensionValidForFIF(FREE_IMAGE_FORMAT fif, string extension, StringComparison comparisonType)
{
if (extension == null)
{
throw new ArgumentNullException("extension");
}
bool result = false;
// Split up the string and compare each with the given extension
string tempList = GetFIFExtensionList(fif);
if (tempList != null)
{
string[] extensionList = tempList.Split(',');
foreach (string ext in extensionList)
{
if (extension.Equals(ext, comparisonType))
{
result = true;
break;
}
}
}
return result;
}
/// <summary>
/// Checks if a filename is valid for a certain format.
/// </summary>
/// <param name="fif">The desired format.</param>
/// <param name="filename">The desired filename.</param>
/// <returns>True if the filename is valid for the given format, false otherwise.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="filename"/> is null.</exception>
public static bool IsFilenameValidForFIF(FREE_IMAGE_FORMAT fif, string filename)
{
return IsFilenameValidForFIF(fif, filename, StringComparison.CurrentCultureIgnoreCase);
}
/// <summary>
/// Checks if a filename is valid for a certain format.
/// </summary>
/// <param name="fif">The desired format.</param>
/// <param name="filename">The desired filename.</param>
/// <param name="comparisonType">The string comparison type.</param>
/// <returns>True if the filename is valid for the given format, false otherwise.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="filename"/> is null.</exception>
public static bool IsFilenameValidForFIF(FREE_IMAGE_FORMAT fif, string filename, StringComparison comparisonType)
{
if (filename == null)
{
throw new ArgumentNullException("filename");
}
bool result = false;
// Extract the filenames extension if it exists
string extension = Path.GetExtension(filename);
if (extension.Length != 0)
{
extension = extension.Remove(0, 1);
result = IsExtensionValidForFIF(fif, extension, comparisonType);
}
return result;
}
/// <summary>
/// This function returns the primary (main or most commonly used?) extension of a certain
/// image format (fif). This is done by returning the first of all possible extensions
/// returned by GetFIFExtensionList().
/// That assumes, that the plugin returns the extensions in ordered form.</summary>
/// <param name="fif">The image format to obtain the primary extension for.</param>
/// <returns>The primary extension of the specified image format.</returns>
public static string GetPrimaryExtensionFromFIF(FREE_IMAGE_FORMAT fif)
{
string result = null;
string extensions = GetFIFExtensionList(fif);
if (extensions != null)
{
int position = extensions.IndexOf(',');
if (position < 0)
{
result = extensions;
}
else
{
result = extensions.Substring(0, position);
}
}
return result;
}
#endregion
#region Multipage functions
/// <summary>
/// Loads a FreeImage multi-paged bitmap.
/// </summary>
/// <param name="filename">The complete name of the file to load.</param>
/// <returns>Handle to a FreeImage multi-paged bitmap.</returns>
/// <exception cref="FileNotFoundException">
/// <paramref name="filename"/> does not exists while opening.</exception>
public static FIMULTIBITMAP OpenMultiBitmapEx(string filename)
{
FREE_IMAGE_FORMAT format = FREE_IMAGE_FORMAT.FIF_UNKNOWN;
return OpenMultiBitmapEx(
filename,
ref format,
FREE_IMAGE_LOAD_FLAGS.DEFAULT,
false,
false,
false);
}
/// <summary>
/// Loads a FreeImage multi-paged bitmap.
/// </summary>
/// <param name="filename">The complete name of the file to load.</param>
/// <param name="keep_cache_in_memory">When true performance is increased at the cost of memory.</param>
/// <returns>Handle to a FreeImage multi-paged bitmap.</returns>
/// <exception cref="FileNotFoundException">
/// <paramref name="filename"/> does not exists while opening.</exception>
public static FIMULTIBITMAP OpenMultiBitmapEx(string filename, bool keep_cache_in_memory)
{
FREE_IMAGE_FORMAT format = FREE_IMAGE_FORMAT.FIF_UNKNOWN;
return OpenMultiBitmapEx(
filename,
ref format,
FREE_IMAGE_LOAD_FLAGS.DEFAULT,
false,
false,
keep_cache_in_memory);
}
/// <summary>
/// Loads a FreeImage multi-paged bitmap.
/// </summary>
/// <param name="filename">The complete name of the file to load.</param>
/// <param name="read_only">When true the bitmap will be loaded read only.</param>
/// <param name="keep_cache_in_memory">When true performance is increased at the cost of memory.</param>
/// <returns>Handle to a FreeImage multi-paged bitmap.</returns>
/// <exception cref="FileNotFoundException">
/// <paramref name="filename"/> does not exists while opening.</exception>
public static FIMULTIBITMAP OpenMultiBitmapEx(
string filename,
bool read_only,
bool keep_cache_in_memory)
{
FREE_IMAGE_FORMAT format = FREE_IMAGE_FORMAT.FIF_UNKNOWN;
return OpenMultiBitmapEx(
filename,
ref format,
FREE_IMAGE_LOAD_FLAGS.DEFAULT,
false,
read_only,
keep_cache_in_memory);
}
/// <summary>
/// Loads a FreeImage multi-paged bitmap.
/// </summary>
/// <param name="filename">The complete name of the file to load.</param>
/// <param name="create_new">When true a new bitmap is created.</param>
/// <param name="read_only">When true the bitmap will be loaded read only.</param>
/// <param name="keep_cache_in_memory">When true performance is increased at the cost of memory.</param>
/// <returns>Handle to a FreeImage multi-paged bitmap.</returns>
/// <exception cref="FileNotFoundException">
/// <paramref name="filename"/> does not exists while opening.</exception>
public static FIMULTIBITMAP OpenMultiBitmapEx(
string filename,
bool create_new,
bool read_only,
bool keep_cache_in_memory)
{
FREE_IMAGE_FORMAT format = FREE_IMAGE_FORMAT.FIF_UNKNOWN;
return OpenMultiBitmapEx(
filename,
ref format,
FREE_IMAGE_LOAD_FLAGS.DEFAULT,
create_new,
read_only,
keep_cache_in_memory);
}
/// <summary>
/// Loads a FreeImage multi-paged bitmap.
/// In case the loading format is <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/> the files real
/// format is being analysed. If no plugin can read the file, format remains
/// <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/> and 0 is returned.
/// </summary>
/// <param name="filename">The complete name of the file to load.</param>
/// <param name="format">Format of the image. If the format is unknown use
/// <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/>.
/// In case a suitable format was found by LoadEx it will be returned in format.</param>
/// <param name="create_new">When true a new bitmap is created.</param>
/// <param name="read_only">When true the bitmap will be loaded read only.</param>
/// <param name="keep_cache_in_memory">When true performance is increased at the cost of memory.</param>
/// <returns>Handle to a FreeImage multi-paged bitmap.</returns>
/// <exception cref="FileNotFoundException">
/// <paramref name="filename"/> does not exists while opening.</exception>
public static FIMULTIBITMAP OpenMultiBitmapEx(
string filename,
ref FREE_IMAGE_FORMAT format,
bool create_new,
bool read_only,
bool keep_cache_in_memory)
{
return OpenMultiBitmapEx(
filename,
ref format,
FREE_IMAGE_LOAD_FLAGS.DEFAULT,
create_new,
read_only,
keep_cache_in_memory);
}
/// <summary>
/// Loads a FreeImage multi-paged bitmap.
/// In case the loading format is <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/> the files
/// real format is being analysed. If no plugin can read the file, format remains
/// <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/> and 0 is returned.
/// Load flags can be provided by the flags parameter.
/// </summary>
/// <param name="filename">The complete name of the file to load.</param>
/// <param name="format">Format of the image. If the format is unknown use
/// <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/>.
/// In case a suitable format was found by LoadEx it will be returned in format.</param>
/// <param name="flags">Flags to enable or disable plugin-features.</param>
/// <param name="create_new">When true a new bitmap is created.</param>
/// <param name="read_only">When true the bitmap will be loaded read only.</param>
/// <param name="keep_cache_in_memory">When true performance is increased at the cost of memory.</param>
/// <returns>Handle to a FreeImage multi-paged bitmap.</returns>
/// <exception cref="FileNotFoundException">
/// <paramref name="filename"/> does not exists while opening.</exception>
public static FIMULTIBITMAP OpenMultiBitmapEx(
string filename,
ref FREE_IMAGE_FORMAT format,
FREE_IMAGE_LOAD_FLAGS flags,
bool create_new,
bool read_only,
bool keep_cache_in_memory)
{
if (!File.Exists(filename) && !create_new)
{
throw new FileNotFoundException(filename + " could not be found.");
}
if (format == FREE_IMAGE_FORMAT.FIF_UNKNOWN)
{
// Check if a plugin can read the data
format = GetFileType(filename, 0);
}
FIMULTIBITMAP dib = new FIMULTIBITMAP();
if (FIFSupportsReading(format))
{
dib = OpenMultiBitmap(format, filename, create_new, read_only, keep_cache_in_memory, flags);
}
return dib;
}
/// <summary>
/// Loads a FreeImage multi-paged bitmap.
/// </summary>
/// <param name="stream">The stream to load the bitmap from.</param>
/// <returns>Handle to a FreeImage multi-paged bitmap.</returns>
public static FIMULTIBITMAP OpenMultiBitmapFromStream(Stream stream)
{
FREE_IMAGE_FORMAT format = FREE_IMAGE_FORMAT.FIF_UNKNOWN;
return OpenMultiBitmapFromStream(stream, ref format, FREE_IMAGE_LOAD_FLAGS.DEFAULT);
}
/// <summary>
/// Loads a FreeImage multi-paged bitmap.
/// In case the loading format is <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/> the files
/// real format is being analysed. If no plugin can read the file, format remains
/// <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/> and 0 is returned.
/// Load flags can be provided by the flags parameter.
/// </summary>
/// <param name="stream">The stream to load the bitmap from.</param>
/// <param name="format">Format of the image. If the format is unknown use
/// <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/></param>.
/// <param name="flags">Flags to enable or disable plugin-features.</param>
/// <returns>Handle to a FreeImage multi-paged bitmap.</returns>
public static FIMULTIBITMAP OpenMultiBitmapFromStream(Stream stream, ref FREE_IMAGE_FORMAT format, FREE_IMAGE_LOAD_FLAGS flags)
{
if (stream == null)
return FIMULTIBITMAP.Zero;
if (!stream.CanSeek)
stream = new StreamWrapper(stream, true);
FIMULTIBITMAP mdib = FIMULTIBITMAP.Zero;
FreeImageIO io = FreeImageStreamIO.io;
fi_handle handle = new fi_handle(stream);
try
{
if (format == FREE_IMAGE_FORMAT.FIF_UNKNOWN)
{
format = GetFileTypeFromHandle(ref io, handle, checked((int)stream.Length));
}
mdib = OpenMultiBitmapFromHandle(format, ref io, handle, flags);
if (mdib.IsNull)
{
handle.Dispose();
}
else
{
lock (streamHandles)
{
streamHandles.Add(mdib, handle);
}
}
return mdib;
}
catch
{
if (!mdib.IsNull)
CloseMultiBitmap(mdib, FREE_IMAGE_SAVE_FLAGS.DEFAULT);
if (handle != null)
handle.Dispose();
throw;
}
}
/// <summary>
/// Closes a previously opened multi-page bitmap and, when the bitmap was not opened read-only, applies any changes made to it.
/// </summary>
/// <param name="bitmap">Handle to a FreeImage multi-paged bitmap.</param>
/// <param name="flags">Flags to enable or disable plugin-features.</param>
/// <returns>Returns true on success, false on failure.</returns>
public static bool CloseMultiBitmap(FIMULTIBITMAP bitmap, FREE_IMAGE_SAVE_FLAGS flags)
{
if (CloseMultiBitmap_(bitmap, flags))
{
fi_handle handle;
lock (streamHandles)
{
if (streamHandles.TryGetValue(bitmap, out handle))
{
streamHandles.Remove(bitmap);
handle.Dispose();
}
}
return true;
}
return false;
}
/// <summary>
/// Closes a previously opened multi-page bitmap and, when the bitmap was not opened read-only,
/// applies any changes made to it.
/// On success the handle will be reset to null.
/// </summary>
/// <param name="bitmap">Handle to a FreeImage multi-paged bitmap.</param>
/// <returns>Returns true on success, false on failure.</returns>
public static bool CloseMultiBitmapEx(ref FIMULTIBITMAP bitmap)
{
return CloseMultiBitmapEx(ref bitmap, FREE_IMAGE_SAVE_FLAGS.DEFAULT);
}
/// <summary>
/// Closes a previously opened multi-page bitmap and, when the bitmap was not opened read-only,
/// applies any changes made to it.
/// On success the handle will be reset to null.
/// </summary>
/// <param name="bitmap">Handle to a FreeImage multi-paged bitmap.</param>
/// <param name="flags">Flags to enable or disable plugin-features.</param>
/// <returns>Returns true on success, false on failure.</returns>
public static bool CloseMultiBitmapEx(ref FIMULTIBITMAP bitmap, FREE_IMAGE_SAVE_FLAGS flags)
{
bool result = false;
if (!bitmap.IsNull)
{
if (CloseMultiBitmap(bitmap, flags))
{
bitmap.SetNull();
result = true;
}
}
return result;
}
/// <summary>
/// Retrieves the number of pages that are locked in a multi-paged bitmap.
/// </summary>
/// <param name="dib">Handle to a FreeImage multi-paged bitmap.</param>
/// <returns>Number of locked pages.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> is null.</exception>
public static int GetLockedPageCount(FIMULTIBITMAP dib)
{
if (dib.IsNull)
{
throw new ArgumentNullException("dib");
}
int result = 0;
GetLockedPageNumbers(dib, null, ref result);
return result;
}
/// <summary>
/// Retrieves a list locked pages of a multi-paged bitmap.
/// </summary>
/// <param name="dib">Handle to a FreeImage multi-paged bitmap.</param>
/// <returns>List containing the indexes of the locked pages.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> is null.</exception>
public static int[] GetLockedPages(FIMULTIBITMAP dib)
{
if (dib.IsNull)
{
throw new ArgumentNullException("dib");
}
// Get the number of pages and create an array to save the information
int count = 0;
int[] result = null;
// Get count
if (GetLockedPageNumbers(dib, result, ref count))
{
result = new int[count];
// Fill array
if (!GetLockedPageNumbers(dib, result, ref count))
{
result = null;
}
}
return result;
}
/// <summary>
/// Loads a FreeImage multi-paged bitmap from a stream and returns the
/// FreeImage memory stream used as temporary buffer.
/// The bitmap can not be modified by calling
/// <see cref="FreeImage.AppendPage(FIMULTIBITMAP,FIBITMAP)"/>,
/// <see cref="FreeImage.InsertPage(FIMULTIBITMAP,Int32,FIBITMAP)"/>,
/// <see cref="FreeImage.MovePage(FIMULTIBITMAP,Int32,Int32)"/> or
/// <see cref="FreeImage.DeletePage(FIMULTIBITMAP,Int32)"/>.
/// </summary>
/// <param name="stream">The stream to read from.</param>
/// <param name="format">Format of the image.</param>
/// <param name="flags">Flags to enable or disable plugin-features.</param>
/// <param name="memory">The temporary memory buffer used to load the bitmap.</param>
/// <returns>Handle to a FreeImage multi-paged bitmap.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="stream"/> is null.</exception>
/// <exception cref="ArgumentException">
/// <paramref name="stream"/> can not read.</exception>
public static FIMULTIBITMAP LoadMultiBitmapFromStream(
Stream stream,
FREE_IMAGE_FORMAT format,
FREE_IMAGE_LOAD_FLAGS flags,
out FIMEMORY memory)
{
if (stream == null)
{
throw new ArgumentNullException("stream");
}
if (!stream.CanRead)
{
throw new ArgumentException("stream");
}
const int blockSize = 1024;
int bytesRead;
byte[] buffer = new byte[blockSize];
stream = stream.CanSeek ? stream : new StreamWrapper(stream, true);
memory = OpenMemory(IntPtr.Zero, 0);
do
{
bytesRead = stream.Read(buffer, 0, blockSize);
WriteMemory(buffer, (uint)blockSize, (uint)1, memory);
}
while (bytesRead == blockSize);
return LoadMultiBitmapFromMemory(format, memory, flags);
}
#endregion
#region Filetype functions
/// <summary>
/// Orders FreeImage to analyze the bitmap signature.
/// In case the stream is not seekable, the stream will have been used
/// and must be recreated for loading.
/// </summary>
/// <param name="stream">Name of the stream to analyze.</param>
/// <returns>Type of the bitmap.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="stream"/> is null.</exception>
/// <exception cref="ArgumentException">
/// <paramref name="stream"/> can not read.</exception>
public static FREE_IMAGE_FORMAT GetFileTypeFromStream(Stream stream)
{
if (stream == null)
{
throw new ArgumentNullException("stream");
}
if (!stream.CanRead)
{
throw new ArgumentException("stream is not capable of reading.");
}
// Wrap the stream if it cannot seek
stream = (stream.CanSeek) ? stream : new StreamWrapper(stream, true);
// Create a 'FreeImageIO' structure for the stream
FreeImageIO io = FreeImageStreamIO.io;
using (fi_handle handle = new fi_handle(stream))
{
return GetFileTypeFromHandle(ref io, handle, 0);
}
}
#endregion
#region Pixel access functions
/// <summary>
/// Retrieves an hBitmap for a FreeImage bitmap.
/// Call FreeHbitmap(IntPtr) to free the handle.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <param name="hdc">A reference device context.
/// Use IntPtr.Zero if no reference is available.</param>
/// <param name="unload">When true dib will be unloaded if the function succeeded.</param>
/// <returns>The hBitmap for the FreeImage bitmap.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> is null.</exception>
public static unsafe IntPtr GetHbitmap(FIBITMAP dib, IntPtr hdc, bool unload)
{
if (dib.IsNull)
{
throw new ArgumentNullException("dib");
}
IntPtr hBitmap = IntPtr.Zero;
bool release = false;
IntPtr ppvBits = IntPtr.Zero;
// Check if we have destination
if (release = (hdc == IntPtr.Zero))
{
// We don't so request dc
hdc = GetDC(IntPtr.Zero);
}
if (hdc != IntPtr.Zero)
{
// Get pointer to the infoheader of the bitmap
IntPtr info = GetInfo(dib);
// Create a bitmap in the dc
hBitmap = CreateDIBSection(hdc, info, DIB_RGB_COLORS, out ppvBits, IntPtr.Zero, 0);
if (hBitmap != IntPtr.Zero && ppvBits != IntPtr.Zero)
{
// Copy the data into the dc
CopyMemory(ppvBits, GetBits(dib), (GetHeight(dib) * GetPitch(dib)));
// Success: we unload the bitmap
if (unload)
{
Unload(dib);
}
}
// We have to release the dc
if (release)
{
ReleaseDC(IntPtr.Zero, hdc);
}
}
return hBitmap;
}
/// <summary>
/// Returns an HBITMAP created by the <c>CreateDIBitmap()</c> function which in turn
/// has always the same color depth as the reference DC, which may be provided
/// through <paramref name="hdc"/>. The desktop DC will be used,
/// if <c>IntPtr.Zero</c> DC is specified.
/// Call <see cref="FreeImage.FreeHbitmap(IntPtr)"/> to free the handle.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <param name="hdc">Handle to a device context.</param>
/// <param name="unload">When true the structure will be unloaded on success.
/// If the function failed and returned false, the bitmap was not unloaded.</param>
/// <returns>If the function succeeds, the return value is a handle to the
/// compatible bitmap. If the function fails, the return value is <see cref="IntPtr.Zero"/>.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> is null.</exception>
public static IntPtr GetBitmapForDevice(FIBITMAP dib, IntPtr hdc, bool unload)
{
if (dib.IsNull)
{
throw new ArgumentNullException("dib");
}
IntPtr hbitmap = IntPtr.Zero;
bool release = false;
if (release = (hdc == IntPtr.Zero))
{
hdc = GetDC(IntPtr.Zero);
}
if (hdc != IntPtr.Zero)
{
hbitmap = CreateDIBitmap(
hdc,
GetInfoHeader(dib),
CBM_INIT,
GetBits(dib),
GetInfo(dib),
DIB_RGB_COLORS);
if (unload)
{
Unload(dib);
}
if (release)
{
ReleaseDC(IntPtr.Zero, hdc);
}
}
return hbitmap;
}
/// <summary>
/// Creates a FreeImage DIB from a Device Context/Compatible Bitmap.
/// </summary>
/// <param name="hbitmap">Handle to the bitmap.</param>
/// <param name="hdc">Handle to a device context.</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="hbitmap"/> is null.</exception>
public unsafe static FIBITMAP CreateFromHbitmap(IntPtr hbitmap, IntPtr hdc)
{
if (hbitmap == IntPtr.Zero)
{
throw new ArgumentNullException("hbitmap");
}
FIBITMAP dib = new FIBITMAP();
BITMAP bm;
uint colors;
bool release;
if (GetObject(hbitmap, sizeof(BITMAP), (IntPtr)(&bm)) != 0)
{
dib = Allocate(bm.bmWidth, bm.bmHeight, bm.bmBitsPixel, 0, 0, 0);
if (!dib.IsNull)
{
colors = GetColorsUsed(dib);
if (release = (hdc == IntPtr.Zero))
{
hdc = GetDC(IntPtr.Zero);
}
if (GetDIBits(
hdc,
hbitmap,
0,
(uint)bm.bmHeight,
GetBits(dib),
GetInfo(dib),
DIB_RGB_COLORS) != 0)
{
if (colors != 0)
{
BITMAPINFOHEADER* bmih = (BITMAPINFOHEADER*)GetInfo(dib);
bmih[0].biClrImportant = bmih[0].biClrUsed = colors;
}
}
else
{
UnloadEx(ref dib);
}
if (release)
{
ReleaseDC(IntPtr.Zero, hdc);
}
}
}
return dib;
}
/// <summary>
/// Frees a bitmap handle.
/// </summary>
/// <param name="hbitmap">Handle to a bitmap.</param>
/// <returns>True on success, false on failure.</returns>
public static bool FreeHbitmap(IntPtr hbitmap)
{
return DeleteObject(hbitmap);
}
#endregion
#region Bitmap information functions
/// <summary>
/// Retrieves a DIB's resolution in X-direction measured in 'dots per inch' (DPI) and not in
/// 'dots per meter'.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <returns>The resolution in 'dots per inch'.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> is null.</exception>
public static uint GetResolutionX(FIBITMAP dib)
{
if (dib.IsNull)
{
throw new ArgumentNullException("dib");
}
return (uint)(0.5d + 0.0254d * GetDotsPerMeterX(dib));
}
/// <summary>
/// Retrieves a DIB's resolution in Y-direction measured in 'dots per inch' (DPI) and not in
/// 'dots per meter'.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <returns>The resolution in 'dots per inch'.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> is null.</exception>
public static uint GetResolutionY(FIBITMAP dib)
{
if (dib.IsNull)
{
throw new ArgumentNullException("dib");
}
return (uint)(0.5d + 0.0254d * GetDotsPerMeterY(dib));
}
/// <summary>
/// Sets a DIB's resolution in X-direction measured in 'dots per inch' (DPI) and not in
/// 'dots per meter'.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <param name="res">The new resolution in 'dots per inch'.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> is null.</exception>
public static void SetResolutionX(FIBITMAP dib, uint res)
{
if (dib.IsNull)
{
throw new ArgumentNullException("dib");
}
SetDotsPerMeterX(dib, (uint)((double)res / 0.0254d + 0.5d));
}
/// <summary>
/// Sets a DIB's resolution in Y-direction measured in 'dots per inch' (DPI) and not in
/// 'dots per meter'.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <param name="res">The new resolution in 'dots per inch'.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> is null.</exception>
public static void SetResolutionY(FIBITMAP dib, uint res)
{
if (dib.IsNull)
{
throw new ArgumentNullException("dib");
}
SetDotsPerMeterY(dib, (uint)((double)res / 0.0254d + 0.5d));
}
/// <summary>
/// Returns whether the image is a greyscale image or not.
/// The function scans all colors in the bitmaps palette for entries where
/// red, green and blue are not all the same (not a grey color).
/// Supports 1-, 4- and 8-bit bitmaps.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <returns>True if the image is a greyscale image, else false.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> is null.</exception>
public static unsafe bool IsGreyscaleImage(FIBITMAP dib)
{
if (dib.IsNull)
{
throw new ArgumentNullException("dib");
}
bool result = true;
uint bpp = GetBPP(dib);
switch (bpp)
{
case 1:
case 4:
case 8:
RGBQUAD* palette = (RGBQUAD*)GetPalette(dib);
uint paletteLength = GetColorsUsed(dib);
for (int i = 0; i < paletteLength; i++)
{
if (palette[i].rgbRed != palette[i].rgbGreen ||
palette[i].rgbRed != palette[i].rgbBlue)
{
result = false;
break;
}
}
break;
default:
result = false;
break;
}
return result;
}
/// <summary>
/// Returns a structure that represents the palette of a FreeImage bitmap.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <returns>A structure representing the bitmaps palette.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> is null.</exception>
public static Palette GetPaletteEx(FIBITMAP dib)
{
return new Palette(dib);
}
/// <summary>
/// Returns the <see cref="BITMAPINFOHEADER"/> structure of a FreeImage bitmap.
/// The structure is a copy, so changes will have no effect on
/// the bitmap itself.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <returns><see cref="BITMAPINFOHEADER"/> structure of the bitmap.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> is null.</exception>
public static unsafe BITMAPINFOHEADER GetInfoHeaderEx(FIBITMAP dib)
{
if (dib.IsNull)
{
throw new ArgumentNullException("dib");
}
return *(BITMAPINFOHEADER*)GetInfoHeader(dib);
}
/// <summary>
/// Returns the <see cref="BITMAPINFO"/> structure of a FreeImage bitmap.
/// The structure is a copy, so changes will have no effect on
/// the bitmap itself.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <returns><see cref="BITMAPINFO"/> structure of the bitmap.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> is null.</exception>
public static BITMAPINFO GetInfoEx(FIBITMAP dib)
{
if (dib.IsNull)
{
throw new ArgumentNullException("dib");
}
BITMAPINFO result = new BITMAPINFO();
result.bmiHeader = GetInfoHeaderEx(dib);
IntPtr ptr = GetPalette(dib);
if (ptr == IntPtr.Zero)
{
result.bmiColors = new RGBQUAD[0];
}
else
{
result.bmiColors = new MemoryArray<RGBQUAD>(ptr, (int)result.bmiHeader.biClrUsed).Data;
}
return result;
}
/// <summary>
/// Returns the pixelformat of the bitmap.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <returns><see cref="System.Drawing.Imaging.PixelFormat"/> of the bitmap.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> is null.</exception>
public static PixelFormat GetPixelFormat(FIBITMAP dib)
{
if (dib.IsNull)
{
throw new ArgumentNullException("dib");
}
PixelFormat result = PixelFormat.Undefined;
if (GetImageType(dib) == FREE_IMAGE_TYPE.FIT_BITMAP)
{
switch (GetBPP(dib))
{
case 1:
result = PixelFormat.Format1bppIndexed;
break;
case 4:
result = PixelFormat.Format4bppIndexed;
break;
case 8:
result = PixelFormat.Format8bppIndexed;
break;
case 16:
if ((GetBlueMask(dib) == FI16_565_BLUE_MASK) &&
(GetGreenMask(dib) == FI16_565_GREEN_MASK) &&
(GetRedMask(dib) == FI16_565_RED_MASK))
{
result = PixelFormat.Format16bppRgb565;
}
if ((GetBlueMask(dib) == FI16_555_BLUE_MASK) &&
(GetGreenMask(dib) == FI16_555_GREEN_MASK) &&
(GetRedMask(dib) == FI16_555_RED_MASK))
{
result = PixelFormat.Format16bppRgb555;
}
break;
case 24:
result = PixelFormat.Format24bppRgb;
break;
case 32:
result = PixelFormat.Format32bppArgb;
break;
}
}
return result;
}
/// <summary>
/// Retrieves all parameters needed to create a new FreeImage bitmap from
/// the format of a .NET <see cref="System.Drawing.Image"/>.
/// </summary>
/// <param name="format">The <see cref="System.Drawing.Imaging.PixelFormat"/>
/// of the .NET <see cref="System.Drawing.Image"/>.</param>
/// <param name="type">Returns the type used for the new bitmap.</param>
/// <param name="bpp">Returns the color depth for the new bitmap.</param>
/// <param name="red_mask">Returns the red_mask for the new bitmap.</param>
/// <param name="green_mask">Returns the green_mask for the new bitmap.</param>
/// <param name="blue_mask">Returns the blue_mask for the new bitmap.</param>
/// <returns>True in case a matching conversion exists; else false.
/// </returns>
public static bool GetFormatParameters(
PixelFormat format,
out FREE_IMAGE_TYPE type,
out uint bpp,
out uint red_mask,
out uint green_mask,
out uint blue_mask)
{
bool result = false;
type = FREE_IMAGE_TYPE.FIT_UNKNOWN;
bpp = 0;
red_mask = 0;
green_mask = 0;
blue_mask = 0;
switch (format)
{
case PixelFormat.Format1bppIndexed:
type = FREE_IMAGE_TYPE.FIT_BITMAP;
bpp = 1;
result = true;
break;
case PixelFormat.Format4bppIndexed:
type = FREE_IMAGE_TYPE.FIT_BITMAP;
bpp = 4;
result = true;
break;
case PixelFormat.Format8bppIndexed:
type = FREE_IMAGE_TYPE.FIT_BITMAP;
bpp = 8;
result = true;
break;
case PixelFormat.Format16bppRgb565:
type = FREE_IMAGE_TYPE.FIT_BITMAP;
bpp = 16;
red_mask = FI16_565_RED_MASK;
green_mask = FI16_565_GREEN_MASK;
blue_mask = FI16_565_BLUE_MASK;
result = true;
break;
case PixelFormat.Format16bppRgb555:
case PixelFormat.Format16bppArgb1555:
type = FREE_IMAGE_TYPE.FIT_BITMAP;
bpp = 16;
red_mask = FI16_555_RED_MASK;
green_mask = FI16_555_GREEN_MASK;
blue_mask = FI16_555_BLUE_MASK;
result = true;
break;
case PixelFormat.Format24bppRgb:
type = FREE_IMAGE_TYPE.FIT_BITMAP;
bpp = 24;
red_mask = FI_RGBA_RED_MASK;
green_mask = FI_RGBA_GREEN_MASK;
blue_mask = FI_RGBA_BLUE_MASK;
result = true;
break;
case PixelFormat.Format32bppRgb:
case PixelFormat.Format32bppArgb:
case PixelFormat.Format32bppPArgb:
type = FREE_IMAGE_TYPE.FIT_BITMAP;
bpp = 32;
red_mask = FI_RGBA_RED_MASK;
green_mask = FI_RGBA_GREEN_MASK;
blue_mask = FI_RGBA_BLUE_MASK;
result = true;
break;
case PixelFormat.Format16bppGrayScale:
type = FREE_IMAGE_TYPE.FIT_UINT16;
bpp = 16;
result = true;
break;
case PixelFormat.Format48bppRgb:
type = FREE_IMAGE_TYPE.FIT_RGB16;
bpp = 48;
result = true;
break;
case PixelFormat.Format64bppArgb:
case PixelFormat.Format64bppPArgb:
type = FREE_IMAGE_TYPE.FIT_RGBA16;
bpp = 64;
result = true;
break;
}
return result;
}
/// <summary>
/// Returns the <see cref="FREE_IMAGE_FORMAT"/> for the specified
/// <see cref="ImageFormat"/>.
/// </summary>
/// <param name="imageFormat">The <see cref="ImageFormat"/>
/// for which to return the corresponding <see cref="FREE_IMAGE_FORMAT"/>.</param>
/// <returns>The <see cref="FREE_IMAGE_FORMAT"/> for the specified
/// <see cref="ImageFormat"/></returns>
public static FREE_IMAGE_FORMAT GetFormat(ImageFormat imageFormat)
{
if (imageFormat != null)
{
if (imageFormat.Equals(ImageFormat.Bmp))
return FREE_IMAGE_FORMAT.FIF_BMP;
if (imageFormat.Equals(ImageFormat.Gif))
return FREE_IMAGE_FORMAT.FIF_GIF;
if (imageFormat.Equals(ImageFormat.Icon))
return FREE_IMAGE_FORMAT.FIF_ICO;
if (imageFormat.Equals(ImageFormat.Jpeg))
return FREE_IMAGE_FORMAT.FIF_JPEG;
if (imageFormat.Equals(ImageFormat.Png))
return FREE_IMAGE_FORMAT.FIF_PNG;
if (imageFormat.Equals(ImageFormat.Tiff))
return FREE_IMAGE_FORMAT.FIF_TIFF;
}
return FREE_IMAGE_FORMAT.FIF_UNKNOWN;
}
/// <summary>
/// Retrieves all parameters needed to create a new FreeImage bitmap from
/// raw bits <see cref="System.Drawing.Image"/>.
/// </summary>
/// <param name="type">The <see cref="FREE_IMAGE_TYPE"/>
/// of the data in memory.</param>
/// <param name="bpp">The color depth for the data.</param>
/// <param name="red_mask">Returns the red_mask for the data.</param>
/// <param name="green_mask">Returns the green_mask for the data.</param>
/// <param name="blue_mask">Returns the blue_mask for the data.</param>
/// <returns>True in case a matching conversion exists; else false.
/// </returns>
public static bool GetTypeParameters(
FREE_IMAGE_TYPE type,
int bpp,
out uint red_mask,
out uint green_mask,
out uint blue_mask)
{
bool result = false;
red_mask = 0;
green_mask = 0;
blue_mask = 0;
switch (type)
{
case FREE_IMAGE_TYPE.FIT_BITMAP:
switch (bpp)
{
case 1:
case 4:
case 8:
result = true;
break;
case 16:
result = true;
red_mask = FI16_555_RED_MASK;
green_mask = FI16_555_GREEN_MASK;
blue_mask = FI16_555_BLUE_MASK;
break;
case 24:
case 32:
result = true;
red_mask = FI_RGBA_RED_MASK;
green_mask = FI_RGBA_GREEN_MASK;
blue_mask = FI_RGBA_BLUE_MASK;
break;
}
break;
case FREE_IMAGE_TYPE.FIT_UNKNOWN:
break;
default:
result = true;
break;
}
return result;
}
/// <summary>
/// Compares two FreeImage bitmaps.
/// </summary>
/// <param name="dib1">The first bitmap to compare.</param>
/// <param name="dib2">The second bitmap to compare.</param>
/// <param name="flags">Determines which components of the bitmaps will be compared.</param>
/// <returns>True in case both bitmaps match the compare conditions, false otherwise.</returns>
public static bool Compare(FIBITMAP dib1, FIBITMAP dib2, FREE_IMAGE_COMPARE_FLAGS flags)
{
// Check whether one bitmap is null
if (dib1.IsNull ^ dib2.IsNull)
{
return false;
}
// Check whether both pointers are the same
if (dib1 == dib2)
{
return true;
}
if (((flags & FREE_IMAGE_COMPARE_FLAGS.HEADER) > 0) && (!CompareHeader(dib1, dib2)))
{
return false;
}
if (((flags & FREE_IMAGE_COMPARE_FLAGS.PALETTE) > 0) && (!ComparePalette(dib1, dib2)))
{
return false;
}
if (((flags & FREE_IMAGE_COMPARE_FLAGS.DATA) > 0) && (!CompareData(dib1, dib2)))
{
return false;
}
if (((flags & FREE_IMAGE_COMPARE_FLAGS.METADATA) > 0) && (!CompareMetadata(dib1, dib2)))
{
return false;
}
return true;
}
private static unsafe bool CompareHeader(FIBITMAP dib1, FIBITMAP dib2)
{
IntPtr i1 = GetInfoHeader(dib1);
IntPtr i2 = GetInfoHeader(dib2);
return CompareMemory((void*)i1, (void*)i2, sizeof(BITMAPINFOHEADER));
}
private static unsafe bool ComparePalette(FIBITMAP dib1, FIBITMAP dib2)
{
IntPtr pal1 = GetPalette(dib1), pal2 = GetPalette(dib2);
bool hasPalette1 = pal1 != IntPtr.Zero;
bool hasPalette2 = pal2 != IntPtr.Zero;
if (hasPalette1 ^ hasPalette2)
{
return false;
}
if (!hasPalette1)
{
return true;
}
uint colors = GetColorsUsed(dib1);
if (colors != GetColorsUsed(dib2))
{
return false;
}
return CompareMemory((void*)pal1, (void*)pal2, sizeof(RGBQUAD) * colors);
}
private static unsafe bool CompareData(FIBITMAP dib1, FIBITMAP dib2)
{
uint width = GetWidth(dib1);
if (width != GetWidth(dib2))
{
return false;
}
uint height = GetHeight(dib1);
if (height != GetHeight(dib2))
{
return false;
}
uint bpp = GetBPP(dib1);
if (bpp != GetBPP(dib2))
{
return false;
}
if (GetColorType(dib1) != GetColorType(dib2))
{
return false;
}
FREE_IMAGE_TYPE type = GetImageType(dib1);
if (type != GetImageType(dib2))
{
return false;
}
if (GetRedMask(dib1) != GetRedMask(dib2))
{
return false;
}
if (GetGreenMask(dib1) != GetGreenMask(dib2))
{
return false;
}
if (GetBlueMask(dib1) != GetBlueMask(dib2))
{
return false;
}
byte* ptr1, ptr2;
int fullBytes;
int shift;
uint line = GetLine(dib1);
if (type == FREE_IMAGE_TYPE.FIT_BITMAP)
{
switch (bpp)
{
case 32:
for (int i = 0; i < height; i++)
{
ptr1 = (byte*)GetScanLine(dib1, i);
ptr2 = (byte*)GetScanLine(dib2, i);
if (!CompareMemory(ptr1, ptr2, line))
{
return false;
}
}
break;
case 24:
for (int i = 0; i < height; i++)
{
ptr1 = (byte*)GetScanLine(dib1, i);
ptr2 = (byte*)GetScanLine(dib2, i);
if (!CompareMemory(ptr1, ptr2, line))
{
return false;
}
}
break;
case 16:
short* sPtr1, sPtr2;
short mask = (short)(GetRedMask(dib1) | GetGreenMask(dib1) | GetBlueMask(dib1));
if (mask == -1)
{
for (int i = 0; i < height; i++)
{
sPtr1 = (short*)GetScanLine(dib1, i);
sPtr2 = (short*)GetScanLine(dib2, i);
if (!CompareMemory(sPtr1, sPtr1, line))
{
return false;
}
}
}
else
{
for (int i = 0; i < height; i++)
{
sPtr1 = (short*)GetScanLine(dib1, i);
sPtr2 = (short*)GetScanLine(dib2, i);
for (int x = 0; x < width; x++)
{
if ((sPtr1[x] & mask) != (sPtr2[x] & mask))
{
return false;
}
}
}
}
break;
case 8:
for (int i = 0; i < height; i++)
{
ptr1 = (byte*)GetScanLine(dib1, i);
ptr2 = (byte*)GetScanLine(dib2, i);
if (!CompareMemory(ptr1, ptr2, line))
{
return false;
}
}
break;
case 4:
fullBytes = (int)width / 2;
shift = (width % 2) == 0 ? 8 : 4;
for (int i = 0; i < height; i++)
{
ptr1 = (byte*)GetScanLine(dib1, i);
ptr2 = (byte*)GetScanLine(dib2, i);
if (fullBytes != 0)
{
if (!CompareMemory(ptr1, ptr2, fullBytes))
{
return false;
}
ptr1 += fullBytes;
ptr2 += fullBytes;
}
if (shift != 8)
{
if ((ptr1[0] >> shift) != (ptr2[0] >> shift))
{
return false;
}
}
}
break;
case 1:
fullBytes = (int)width / 8;
shift = 8 - ((int)width % 8);
for (int i = 0; i < height; i++)
{
ptr1 = (byte*)GetScanLine(dib1, i);
ptr2 = (byte*)GetScanLine(dib2, i);
if (fullBytes != 0)
{
if (!CompareMemory(ptr1, ptr2, fullBytes))
{
return false;
}
ptr1 += fullBytes;
ptr2 += fullBytes;
}
if (shift != 8)
{
if ((ptr1[0] >> shift) != (ptr2[0] >> shift))
{
return false;
}
}
}
break;
default:
throw new NotSupportedException("Only 1, 4, 8, 16, 24 and 32 bpp bitmaps are supported.");
}
}
else
{
for (int i = 0; i < height; i++)
{
ptr1 = (byte*)GetScanLine(dib1, i);
ptr2 = (byte*)GetScanLine(dib2, i);
if (!CompareMemory(ptr1, ptr2, line))
{
return false;
}
}
}
return true;
}
private static bool CompareMetadata(FIBITMAP dib1, FIBITMAP dib2)
{
MetadataTag tag1, tag2;
foreach (FREE_IMAGE_MDMODEL metadataModel in FREE_IMAGE_MDMODELS)
{
if (GetMetadataCount(metadataModel, dib1) !=
GetMetadataCount(metadataModel, dib2))
{
return false;
}
if (GetMetadataCount(metadataModel, dib1) == 0)
{
continue;
}
FIMETADATA mdHandle = FindFirstMetadata(metadataModel, dib1, out tag1);
if (mdHandle.IsNull)
{
continue;
}
do
{
if ((!GetMetadata(metadataModel, dib2, tag1.Key, out tag2)) || (tag1 != tag2))
{
FindCloseMetadata(mdHandle);
return false;
}
}
while (FindNextMetadata(mdHandle, out tag1));
FindCloseMetadata(mdHandle);
}
return true;
}
/// <summary>
/// Returns the FreeImage bitmap's transparency table.
/// The array is empty in case the bitmap has no transparency table.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <returns>The FreeImage bitmap's transparency table.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> is null.</exception>
public static unsafe byte[] GetTransparencyTableEx(FIBITMAP dib)
{
if (dib.IsNull)
{
throw new ArgumentNullException("dib");
}
uint count = GetTransparencyCount(dib);
byte[] result = new byte[count];
byte* ptr = (byte*)GetTransparencyTable(dib);
fixed (byte* dst = result)
{
CopyMemory(dst, ptr, count);
}
return result;
}
/// <summary>
/// Set the FreeImage bitmap's transparency table. Only affects palletised bitmaps.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <param name="table">The FreeImage bitmap's new transparency table.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> or <paramref name="table"/> is null.</exception>
public static void SetTransparencyTable(FIBITMAP dib, byte[] table)
{
if (dib.IsNull)
{
throw new ArgumentNullException("dib");
}
if (table == null)
{
throw new ArgumentNullException("table");
}
SetTransparencyTable(dib, table, table.Length);
}
/// <summary>
/// This function returns the number of unique colors actually used by the
/// specified 1-, 4-, 8-, 16-, 24- or 32-bit image. This might be different from
/// what function FreeImage_GetColorsUsed() returns, which actually returns the
/// palette size for palletised images. Works for
/// <see cref="FREE_IMAGE_TYPE.FIT_BITMAP"/> type images only.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <returns>Returns the number of unique colors used by the image specified or
/// zero, if the image type cannot be handled.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> is null.</exception>
public static unsafe int GetUniqueColors(FIBITMAP dib)
{
if (dib.IsNull)
{
throw new ArgumentNullException("dib");
}
int result = 0;
if (GetImageType(dib) == FREE_IMAGE_TYPE.FIT_BITMAP)
{
BitArray bitArray;
int uniquePalEnts;
int hashcode;
byte[] lut;
int width = (int)GetWidth(dib);
int height = (int)GetHeight(dib);
switch (GetBPP(dib))
{
case 1:
result = 1;
lut = CreateShrunkenPaletteLUT(dib, out uniquePalEnts);
if (uniquePalEnts == 1)
{
break;
}
if ((*(byte*)GetScanLine(dib, 0) & 0x80) == 0)
{
for (int y = 0; y < height; y++)
{
byte* scanline = (byte*)GetScanLine(dib, y);
int mask = 0x80;
for (int x = 0; x < width; x++)
{
if ((scanline[x / 8] & mask) > 0)
{
return 2;
}
mask = (mask == 0x1) ? 0x80 : (mask >> 1);
}
}
}
else
{
for (int y = 0; y < height; y++)
{
byte* scanline = (byte*)GetScanLine(dib, y);
int mask = 0x80;
for (int x = 0; x < width; x++)
{
if ((scanline[x / 8] & mask) == 0)
{
return 2;
}
mask = (mask == 0x1) ? 0x80 : (mask >> 1);
}
}
}
break;
case 4:
bitArray = new BitArray(0x10);
lut = CreateShrunkenPaletteLUT(dib, out uniquePalEnts);
if (uniquePalEnts == 1)
{
result = 1;
break;
}
for (int y = 0; (y < height) && (result < uniquePalEnts); y++)
{
byte* scanline = (byte*)GetScanLine(dib, y);
bool top = true;
for (int x = 0; (x < width) && (result < uniquePalEnts); x++)
{
if (top)
{
hashcode = lut[scanline[x / 2] >> 4];
}
else
{
hashcode = lut[scanline[x / 2] & 0xF];
}
top = !top;
if (!bitArray[hashcode])
{
bitArray[hashcode] = true;
result++;
}
}
}
break;
case 8:
bitArray = new BitArray(0x100);
lut = CreateShrunkenPaletteLUT(dib, out uniquePalEnts);
if (uniquePalEnts == 1)
{
result = 1;
break;
}
for (int y = 0; (y < height) && (result < uniquePalEnts); y++)
{
byte* scanline = (byte*)GetScanLine(dib, y);
for (int x = 0; (x < width) && (result < uniquePalEnts); x++)
{
hashcode = lut[scanline[x]];
if (!bitArray[hashcode])
{
bitArray[hashcode] = true;
result++;
}
}
}
break;
case 16:
bitArray = new BitArray(0x10000);
for (int y = 0; y < height; y++)
{
short* scanline = (short*)GetScanLine(dib, y);
for (int x = 0; x < width; x++, scanline++)
{
hashcode = *scanline;
if (!bitArray[hashcode])
{
bitArray[hashcode] = true;
result++;
}
}
}
break;
case 24:
bitArray = new BitArray(0x1000000);
for (int y = 0; y < height; y++)
{
byte* scanline = (byte*)GetScanLine(dib, y);
for (int x = 0; x < width; x++, scanline += 3)
{
hashcode = *((int*)scanline) & 0x00FFFFFF;
if (!bitArray[hashcode])
{
bitArray[hashcode] = true;
result++;
}
}
}
break;
case 32:
bitArray = new BitArray(0x1000000);
for (int y = 0; y < height; y++)
{
int* scanline = (int*)GetScanLine(dib, y);
for (int x = 0; x < width; x++, scanline++)
{
hashcode = *scanline & 0x00FFFFFF;
if (!bitArray[hashcode])
{
bitArray[hashcode] = true;
result++;
}
}
}
break;
}
}
return result;
}
/// <summary>
/// Verifies whether the FreeImage bitmap is 16bit 555.
/// </summary>
/// <param name="dib">The FreeImage bitmap to verify.</param>
/// <returns><b>true</b> if the bitmap is RGB16-555; otherwise <b>false</b>.</returns>
public static bool IsRGB555(FIBITMAP dib)
{
return ((GetRedMask(dib) == FI16_555_RED_MASK) &&
(GetGreenMask(dib) == FI16_555_GREEN_MASK) &&
(GetBlueMask(dib) == FI16_555_BLUE_MASK));
}
/// <summary>
/// Verifies whether the FreeImage bitmap is 16bit 565.
/// </summary>
/// <param name="dib">The FreeImage bitmap to verify.</param>
/// <returns><b>true</b> if the bitmap is RGB16-565; otherwise <b>false</b>.</returns>
public static bool IsRGB565(FIBITMAP dib)
{
return ((GetRedMask(dib) == FI16_565_RED_MASK) &&
(GetGreenMask(dib) == FI16_565_GREEN_MASK) &&
(GetBlueMask(dib) == FI16_565_BLUE_MASK));
}
#endregion
#region ICC profile functions
/// <summary>
/// Creates a new ICC-Profile for a FreeImage bitmap.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <param name="data">The data of the new ICC-Profile.</param>
/// <returns>The new ICC-Profile of the bitmap.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> is null.</exception>
public static FIICCPROFILE CreateICCProfileEx(FIBITMAP dib, byte[] data)
{
return new FIICCPROFILE(dib, data);
}
/// <summary>
/// Creates a new ICC-Profile for a FreeImage bitmap.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <param name="data">The data of the new ICC-Profile.</param>
/// <param name="size">The number of bytes of <paramref name="data"/> to use.</param>
/// <returns>The new ICC-Profile of the FreeImage bitmap.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> is null.</exception>
public static FIICCPROFILE CreateICCProfileEx(FIBITMAP dib, byte[] data, int size)
{
return new FIICCPROFILE(dib, data, size);
}
#endregion
#region Conversion functions
/// <summary>
/// Converts a FreeImage bitmap from one color depth to another.
/// If the conversion fails the original FreeImage bitmap is returned.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <param name="conversion">The desired output format.</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> is null.</exception>
public static FIBITMAP ConvertColorDepth(
FIBITMAP dib,
FREE_IMAGE_COLOR_DEPTH conversion)
{
return ConvertColorDepth(
dib,
conversion,
128,
FREE_IMAGE_DITHER.FID_FS,
FREE_IMAGE_QUANTIZE.FIQ_WUQUANT,
false);
}
/// <summary>
/// Converts a FreeImage bitmap from one color depth to another.
/// If the conversion fails the original FreeImage bitmap is returned.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <param name="conversion">The desired output format.</param>
/// <param name="unloadSource">When true the structure will be unloaded on success.</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> is null.</exception>
public static FIBITMAP ConvertColorDepth(
FIBITMAP dib,
FREE_IMAGE_COLOR_DEPTH conversion,
bool unloadSource)
{
return ConvertColorDepth(
dib,
conversion,
128,
FREE_IMAGE_DITHER.FID_FS,
FREE_IMAGE_QUANTIZE.FIQ_WUQUANT,
unloadSource);
}
/// <summary>
/// Converts a FreeImage bitmap from one color depth to another.
/// If the conversion fails the original FreeImage bitmap is returned.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <param name="conversion">The desired output format.</param>
/// <param name="threshold">Threshold value when converting with
/// <see cref="FREE_IMAGE_COLOR_DEPTH.FICD_01_BPP_THRESHOLD"/>.</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> is null.</exception>
public static FIBITMAP ConvertColorDepth(
FIBITMAP dib,
FREE_IMAGE_COLOR_DEPTH conversion,
byte threshold)
{
return ConvertColorDepth(
dib,
conversion,
threshold,
FREE_IMAGE_DITHER.FID_FS,
FREE_IMAGE_QUANTIZE.FIQ_WUQUANT,
false);
}
/// <summary>
/// Converts a FreeImage bitmap from one color depth to another.
/// If the conversion fails the original FreeImage bitmap is returned.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <param name="conversion">The desired output format.</param>
/// <param name="ditherMethod">Dither algorithm when converting
/// with <see cref="FREE_IMAGE_COLOR_DEPTH.FICD_01_BPP_DITHER"/>.</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> is null.</exception>
public static FIBITMAP ConvertColorDepth(
FIBITMAP dib,
FREE_IMAGE_COLOR_DEPTH conversion,
FREE_IMAGE_DITHER ditherMethod)
{
return ConvertColorDepth(
dib,
conversion,
128,
ditherMethod,
FREE_IMAGE_QUANTIZE.FIQ_WUQUANT,
false);
}
/// <summary>
/// Converts a FreeImage bitmap from one color depth to another.
/// If the conversion fails the original FreeImage bitmap is returned.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <param name="conversion">The desired output format.</param>
/// <param name="quantizationMethod">The quantization algorithm for conversion to 8-bit color depth.</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> is null.</exception>
public static FIBITMAP ConvertColorDepth(
FIBITMAP dib,
FREE_IMAGE_COLOR_DEPTH conversion,
FREE_IMAGE_QUANTIZE quantizationMethod)
{
return ConvertColorDepth(
dib,
conversion,
128,
FREE_IMAGE_DITHER.FID_FS,
quantizationMethod,
false);
}
/// <summary>
/// Converts a FreeImage bitmap from one color depth to another.
/// If the conversion fails the original FreeImage bitmap is returned.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <param name="conversion">The desired output format.</param>
/// <param name="threshold">Threshold value when converting with
/// <see cref="FREE_IMAGE_COLOR_DEPTH.FICD_01_BPP_THRESHOLD"/>.</param>
/// <param name="unloadSource">When true the structure will be unloaded on success.</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> is null.</exception>
public static FIBITMAP ConvertColorDepth(
FIBITMAP dib,
FREE_IMAGE_COLOR_DEPTH conversion,
byte threshold,
bool unloadSource)
{
return ConvertColorDepth(
dib,
conversion,
threshold,
FREE_IMAGE_DITHER.FID_FS,
FREE_IMAGE_QUANTIZE.FIQ_WUQUANT,
unloadSource);
}
/// <summary>
/// Converts a FreeImage bitmap from one color depth to another.
/// If the conversion fails the original FreeImage bitmap is returned.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <param name="conversion">The desired output format.</param>
/// <param name="ditherMethod">Dither algorithm when converting with
/// <see cref="FREE_IMAGE_COLOR_DEPTH.FICD_01_BPP_DITHER"/>.</param>
/// <param name="unloadSource">When true the structure will be unloaded on success.</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> is null.</exception>
public static FIBITMAP ConvertColorDepth(
FIBITMAP dib,
FREE_IMAGE_COLOR_DEPTH conversion,
FREE_IMAGE_DITHER ditherMethod,
bool unloadSource)
{
return ConvertColorDepth(
dib,
conversion,
128,
ditherMethod,
FREE_IMAGE_QUANTIZE.FIQ_WUQUANT,
unloadSource);
}
/// <summary>
/// Converts a FreeImage bitmap from one color depth to another.
/// If the conversion fails the original FreeImage bitmap is returned.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <param name="conversion">The desired output format.</param>
/// <param name="quantizationMethod">The quantization algorithm for conversion to 8-bit color depth.</param>
/// <param name="unloadSource">When true the structure will be unloaded on success.</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> is null.</exception>
public static FIBITMAP ConvertColorDepth(
FIBITMAP dib,
FREE_IMAGE_COLOR_DEPTH conversion,
FREE_IMAGE_QUANTIZE quantizationMethod,
bool unloadSource)
{
return ConvertColorDepth(
dib,
conversion,
128,
FREE_IMAGE_DITHER.FID_FS,
quantizationMethod,
unloadSource);
}
/// <summary>
/// Converts a FreeImage bitmap from one color depth to another.
/// If the conversion fails the original FreeImage bitmap is returned.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <param name="conversion">The desired output format.</param>
/// <param name="threshold">Threshold value when converting with
/// <see cref="FREE_IMAGE_COLOR_DEPTH.FICD_01_BPP_THRESHOLD"/>.</param>
/// <param name="ditherMethod">Dither algorithm when converting with
/// <see cref="FREE_IMAGE_COLOR_DEPTH.FICD_01_BPP_DITHER"/>.</param>
/// <param name="quantizationMethod">The quantization algorithm for conversion to 8-bit color depth.</param>
/// <param name="unloadSource">When true the structure will be unloaded on success.</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> is null.</exception>
internal static FIBITMAP ConvertColorDepth(
FIBITMAP dib,
FREE_IMAGE_COLOR_DEPTH conversion,
byte threshold,
FREE_IMAGE_DITHER ditherMethod,
FREE_IMAGE_QUANTIZE quantizationMethod,
bool unloadSource)
{
if (dib.IsNull)
{
throw new ArgumentNullException("dib");
}
FIBITMAP result = new FIBITMAP();
FIBITMAP dibTemp = new FIBITMAP();
uint bpp = GetBPP(dib);
bool reorderPalette = ((conversion & FREE_IMAGE_COLOR_DEPTH.FICD_REORDER_PALETTE) > 0);
bool forceGreyscale = ((conversion & FREE_IMAGE_COLOR_DEPTH.FICD_FORCE_GREYSCALE) > 0);
if (GetImageType(dib) == FREE_IMAGE_TYPE.FIT_BITMAP)
{
switch (conversion & (FREE_IMAGE_COLOR_DEPTH)0xFF)
{
case FREE_IMAGE_COLOR_DEPTH.FICD_01_BPP_THRESHOLD:
if (bpp != 1)
{
if (forceGreyscale)
{
result = Threshold(dib, threshold);
}
else
{
dibTemp = ConvertTo24Bits(dib);
result = ColorQuantizeEx(dibTemp, quantizationMethod, 2, null, 1);
Unload(dibTemp);
}
}
else
{
bool isGreyscale = IsGreyscaleImage(dib);
if ((forceGreyscale && (!isGreyscale)) ||
(reorderPalette && isGreyscale))
{
result = Threshold(dib, threshold);
}
}
break;
case FREE_IMAGE_COLOR_DEPTH.FICD_01_BPP_DITHER:
if (bpp != 1)
{
if (forceGreyscale)
{
result = Dither(dib, ditherMethod);
}
else
{
dibTemp = ConvertTo24Bits(dib);
result = ColorQuantizeEx(dibTemp, quantizationMethod, 2, null, 1);
Unload(dibTemp);
}
}
else
{
bool isGreyscale = IsGreyscaleImage(dib);
if ((forceGreyscale && (!isGreyscale)) ||
(reorderPalette && isGreyscale))
{
result = Dither(dib, ditherMethod);
}
}
break;
case FREE_IMAGE_COLOR_DEPTH.FICD_04_BPP:
if (bpp != 4)
{
// Special case when 1bpp and FIC_PALETTE
if (forceGreyscale ||
((bpp == 1) && (GetColorType(dib) == FREE_IMAGE_COLOR_TYPE.FIC_PALETTE)))
{
dibTemp = ConvertToGreyscale(dib);
result = ConvertTo4Bits(dibTemp);
Unload(dibTemp);
}
else
{
dibTemp = ConvertTo24Bits(dib);
result = ColorQuantizeEx(dibTemp, quantizationMethod, 16, null, 4);
Unload(dibTemp);
}
}
else
{
bool isGreyscale = IsGreyscaleImage(dib);
if ((forceGreyscale && (!isGreyscale)) ||
(reorderPalette && isGreyscale))
{
dibTemp = ConvertToGreyscale(dib);
result = ConvertTo4Bits(dibTemp);
Unload(dibTemp);
}
}
break;
case FREE_IMAGE_COLOR_DEPTH.FICD_08_BPP:
if (bpp != 8)
{
if (forceGreyscale)
{
result = ConvertToGreyscale(dib);
}
else
{
dibTemp = ConvertTo24Bits(dib);
result = ColorQuantize(dibTemp, quantizationMethod);
Unload(dibTemp);
}
}
else
{
bool isGreyscale = IsGreyscaleImage(dib);
if ((forceGreyscale && (!isGreyscale)) || (reorderPalette && isGreyscale))
{
result = ConvertToGreyscale(dib);
}
}
break;
case FREE_IMAGE_COLOR_DEPTH.FICD_16_BPP_555:
if (forceGreyscale)
{
dibTemp = ConvertToGreyscale(dib);
result = ConvertTo16Bits555(dibTemp);
Unload(dibTemp);
}
else if (bpp != 16 || GetRedMask(dib) != FI16_555_RED_MASK || GetGreenMask(dib) != FI16_555_GREEN_MASK || GetBlueMask(dib) != FI16_555_BLUE_MASK)
{
result = ConvertTo16Bits555(dib);
}
break;
case FREE_IMAGE_COLOR_DEPTH.FICD_16_BPP:
if (forceGreyscale)
{
dibTemp = ConvertToGreyscale(dib);
result = ConvertTo16Bits565(dibTemp);
Unload(dibTemp);
}
else if (bpp != 16 || GetRedMask(dib) != FI16_565_RED_MASK || GetGreenMask(dib) != FI16_565_GREEN_MASK || GetBlueMask(dib) != FI16_565_BLUE_MASK)
{
result = ConvertTo16Bits565(dib);
}
break;
case FREE_IMAGE_COLOR_DEPTH.FICD_24_BPP:
if (forceGreyscale)
{
dibTemp = ConvertToGreyscale(dib);
result = ConvertTo24Bits(dibTemp);
Unload(dibTemp);
}
else if (bpp != 24)
{
result = ConvertTo24Bits(dib);
}
break;
case FREE_IMAGE_COLOR_DEPTH.FICD_32_BPP:
if (forceGreyscale)
{
dibTemp = ConvertToGreyscale(dib);
result = ConvertTo32Bits(dibTemp);
Unload(dibTemp);
}
else if (bpp != 32)
{
result = ConvertTo32Bits(dib);
}
break;
}
}
if (result.IsNull)
{
return dib;
}
if (unloadSource)
{
Unload(dib);
}
return result;
}
/// <summary>
/// ColorQuantizeEx is an extension to the <see cref="ColorQuantize(FIBITMAP, FREE_IMAGE_QUANTIZE)"/>
/// method that provides additional options used to quantize a 24-bit image to any
/// number of colors (up to 256), as well as quantize a 24-bit image using a
/// provided palette.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <param name="quantize">Specifies the color reduction algorithm to be used.</param>
/// <param name="PaletteSize">Size of the desired output palette.</param>
/// <param name="ReservePalette">The provided palette.</param>
/// <param name="minColorDepth"><b>true</b> to create a bitmap with the smallest possible
/// color depth for the specified <paramref name="PaletteSize"/>.</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
public static FIBITMAP ColorQuantizeEx(FIBITMAP dib, FREE_IMAGE_QUANTIZE quantize, int PaletteSize, RGBQUAD[] ReservePalette, bool minColorDepth)
{
FIBITMAP result;
if (minColorDepth)
{
int bpp;
if (PaletteSize >= 256)
bpp = 8;
else if (PaletteSize > 2)
bpp = 4;
else
bpp = 1;
result = ColorQuantizeEx(dib, quantize, PaletteSize, ReservePalette, bpp);
}
else
{
result = ColorQuantizeEx(dib, quantize, PaletteSize, ReservePalette, 8);
}
return result;
}
/// <summary>
/// ColorQuantizeEx is an extension to the <see cref="ColorQuantize(FIBITMAP, FREE_IMAGE_QUANTIZE)"/>
/// method that provides additional options used to quantize a 24-bit image to any
/// number of colors (up to 256), as well as quantize a 24-bit image using a
/// partial or full provided palette.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <param name="quantize">Specifies the color reduction algorithm to be used.</param>
/// <param name="PaletteSize">Size of the desired output palette.</param>
/// <param name="ReservePalette">The provided palette.</param>
/// <param name="bpp">The desired color depth of the created image.</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
public static FIBITMAP ColorQuantizeEx(FIBITMAP dib, FREE_IMAGE_QUANTIZE quantize, int PaletteSize, RGBQUAD[] ReservePalette, int bpp)
{
unsafe
{
FIBITMAP result = FIBITMAP.Zero;
FIBITMAP temp = FIBITMAP.Zero;
int reservedSize = (ReservePalette == null) ? 0 : ReservePalette.Length;
if (bpp == 8)
{
result = ColorQuantizeEx(dib, quantize, PaletteSize, reservedSize, ReservePalette);
}
else if (bpp == 4)
{
temp = ColorQuantizeEx(dib, quantize, Math.Min(16, PaletteSize), reservedSize, ReservePalette);
if (!temp.IsNull)
{
result = Allocate((int)GetWidth(temp), (int)GetHeight(temp), 4, 0, 0, 0);
CloneMetadata(result, temp);
CopyMemory(GetPalette(result), GetPalette(temp), sizeof(RGBQUAD) * 16);
for (int y = (int)GetHeight(temp) - 1; y >= 0; y--)
{
Scanline<byte> srcScanline = new Scanline<byte>(temp, y);
Scanline<FI4BIT> dstScanline = new Scanline<FI4BIT>(result, y);
for (int x = (int)GetWidth(temp) - 1; x >= 0; x--)
{
dstScanline[x] = srcScanline[x];
}
}
}
}
else if (bpp == 1)
{
temp = ColorQuantizeEx(dib, quantize, 2, reservedSize, ReservePalette);
if (!temp.IsNull)
{
result = Allocate((int)GetWidth(temp), (int)GetHeight(temp), 1, 0, 0, 0);
CloneMetadata(result, temp);
CopyMemory(GetPalette(result), GetPalette(temp), sizeof(RGBQUAD) * 2);
for (int y = (int)GetHeight(temp) - 1; y >= 0; y--)
{
Scanline<byte> srcScanline = new Scanline<byte>(temp, y);
Scanline<FI1BIT> dstScanline = new Scanline<FI1BIT>(result, y);
for (int x = (int)GetWidth(temp) - 1; x >= 0; x--)
{
dstScanline[x] = srcScanline[x];
}
}
}
}
UnloadEx(ref temp);
return result;
}
}
#endregion
#region Metadata
/// <summary>
/// Copies metadata from one FreeImage bitmap to another.
/// </summary>
/// <param name="src">Source FreeImage bitmap containing the metadata.</param>
/// <param name="dst">FreeImage bitmap to copy the metadata to.</param>
/// <param name="flags">Flags to switch different copy modes.</param>
/// <returns>Returns -1 on failure else the number of copied tags.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="src"/> or <paramref name="dst"/> is null.</exception>
public static int CloneMetadataEx(FIBITMAP src, FIBITMAP dst, FREE_IMAGE_METADATA_COPY flags)
{
if (src.IsNull)
{
throw new ArgumentNullException("src");
}
if (dst.IsNull)
{
throw new ArgumentNullException("dst");
}
FITAG tag = new FITAG(), tag2 = new FITAG();
int copied = 0;
// Clear all existing metadata
if ((flags & FREE_IMAGE_METADATA_COPY.CLEAR_EXISTING) > 0)
{
foreach (FREE_IMAGE_MDMODEL model in FREE_IMAGE_MDMODELS)
{
if (!SetMetadata(model, dst, null, tag))
{
return -1;
}
}
}
bool keep = !((flags & FREE_IMAGE_METADATA_COPY.REPLACE_EXISTING) > 0);
foreach (FREE_IMAGE_MDMODEL model in FREE_IMAGE_MDMODELS)
{
FIMETADATA mData = FindFirstMetadata(model, src, out tag);
if (mData.IsNull) continue;
do
{
string key = GetTagKey(tag);
if (!(keep && GetMetadata(model, dst, key, out tag2)))
{
if (SetMetadata(model, dst, key, tag))
{
copied++;
}
}
}
while (FindNextMetadata(mData, out tag));
FindCloseMetadata(mData);
}
return copied;
}
/// <summary>
/// Returns the comment of a JPEG, PNG or GIF image.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <returns>Comment of the FreeImage bitmp, or null in case no comment exists.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> is null.</exception>
public static string GetImageComment(FIBITMAP dib)
{
string result = null;
if (dib.IsNull)
{
throw new ArgumentNullException("dib");
}
FITAG tag;
if (GetMetadata(FREE_IMAGE_MDMODEL.FIMD_COMMENTS, dib, "Comment", out tag))
{
MetadataTag metadataTag = new MetadataTag(tag, FREE_IMAGE_MDMODEL.FIMD_COMMENTS);
result = metadataTag.Value as string;
}
return result;
}
/// <summary>
/// Sets the comment of a JPEG, PNG or GIF image.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <param name="comment">New comment of the FreeImage bitmap.
/// Use null to remove the comment.</param>
/// <returns>Returns true on success, false on failure.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> is null.</exception>
public static bool SetImageComment(FIBITMAP dib, string comment)
{
if (dib.IsNull)
{
throw new ArgumentNullException("dib");
}
bool result;
if (comment != null)
{
FITAG tag = CreateTag();
MetadataTag metadataTag = new MetadataTag(tag, FREE_IMAGE_MDMODEL.FIMD_COMMENTS);
metadataTag.Value = comment;
result = SetMetadata(FREE_IMAGE_MDMODEL.FIMD_COMMENTS, dib, "Comment", tag);
DeleteTag(tag);
}
else
{
result = SetMetadata(FREE_IMAGE_MDMODEL.FIMD_COMMENTS, dib, "Comment", FITAG.Zero);
}
return result;
}
/// <summary>
/// Retrieve a metadata attached to a FreeImage bitmap.
/// </summary>
/// <param name="model">The metadata model to look for.</param>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <param name="key">The metadata field name.</param>
/// <param name="tag">A <see cref="MetadataTag"/> structure returned by the function.</param>
/// <returns>Returns true on success, false on failure.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> is null.</exception>
public static bool GetMetadata(
FREE_IMAGE_MDMODEL model,
FIBITMAP dib,
string key,
out MetadataTag tag)
{
if (dib.IsNull)
{
throw new ArgumentNullException("dib");
}
FITAG _tag;
bool result;
if (GetMetadata(model, dib, key, out _tag))
{
tag = new MetadataTag(_tag, model);
result = true;
}
else
{
tag = null;
result = false;
}
return result;
}
/// <summary>
/// Attach a new metadata tag to a FreeImage bitmap.
/// </summary>
/// <param name="model">The metadata model used to store the tag.</param>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <param name="key">The tag field name.</param>
/// <param name="tag">The <see cref="MetadataTag"/> to be attached.</param>
/// <returns>Returns true on success, false on failure.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> is null.</exception>
public static bool SetMetadata(
FREE_IMAGE_MDMODEL model,
FIBITMAP dib,
string key,
MetadataTag tag)
{
if (dib.IsNull)
{
throw new ArgumentNullException("dib");
}
return SetMetadata(model, dib, key, tag.tag);
}
/// <summary>
/// Provides information about the first instance of a tag that matches the metadata model.
/// </summary>
/// <param name="model">The model to match.</param>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <param name="tag">Tag that matches the metadata model.</param>
/// <returns>Unique search handle that can be used to call FindNextMetadata or FindCloseMetadata.
/// Null if the metadata model does not exist.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> is null.</exception>
public static FIMETADATA FindFirstMetadata(
FREE_IMAGE_MDMODEL model,
FIBITMAP dib,
out MetadataTag tag)
{
if (dib.IsNull)
{
throw new ArgumentNullException("dib");
}
FITAG _tag;
FIMETADATA result = FindFirstMetadata(model, dib, out _tag);
if (result.IsNull)
{
tag = null;
return result;
}
tag = new MetadataTag(_tag, model);
if (metaDataSearchHandler.ContainsKey(result))
{
metaDataSearchHandler[result] = model;
}
else
{
metaDataSearchHandler.Add(result, model);
}
return result;
}
/// <summary>
/// Find the next tag, if any, that matches the metadata model argument in a previous call
/// to FindFirstMetadata, and then alters the tag object contents accordingly.
/// </summary>
/// <param name="mdhandle">Unique search handle provided by FindFirstMetadata.</param>
/// <param name="tag">Tag that matches the metadata model.</param>
/// <returns>Returns true on success, false on failure.</returns>
public static bool FindNextMetadata(FIMETADATA mdhandle, out MetadataTag tag)
{
FITAG _tag;
bool result;
if (FindNextMetadata(mdhandle, out _tag))
{
tag = new MetadataTag(_tag, metaDataSearchHandler[mdhandle]);
result = true;
}
else
{
tag = null;
result = false;
}
return result;
}
/// <summary>
/// Closes the specified metadata search handle and releases associated resources.
/// </summary>
/// <param name="mdhandle">The handle to close.</param>
public static void FindCloseMetadata(FIMETADATA mdhandle)
{
if (metaDataSearchHandler.ContainsKey(mdhandle))
{
metaDataSearchHandler.Remove(mdhandle);
}
FindCloseMetadata_(mdhandle);
}
/// <summary>
/// This dictionary links FIMETADATA handles and FREE_IMAGE_MDMODEL models.
/// </summary>
private static Dictionary<FIMETADATA, FREE_IMAGE_MDMODEL> metaDataSearchHandler
= new Dictionary<FIMETADATA, FREE_IMAGE_MDMODEL>(1);
#endregion
#region Rotation and Flipping
/// <summary>
/// This function rotates a 1-, 8-bit greyscale or a 24-, 32-bit color image by means of 3 shears.
/// 1-bit images rotation is limited to integer multiple of 90.
/// <c>null</c> is returned for other values.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <param name="angle">The angle of rotation.</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
public static FIBITMAP Rotate(FIBITMAP dib, double angle)
{
return Rotate(dib, angle, IntPtr.Zero);
}
/// <summary>
/// This function rotates a 1-, 8-bit greyscale or a 24-, 32-bit color image by means of 3 shears.
/// 1-bit images rotation is limited to integer multiple of 90.
/// <c>null</c> is returned for other values.
/// </summary>
/// <typeparam name="T">The type of the color to use as background.</typeparam>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <param name="angle">The angle of rotation.</param>
/// <param name="backgroundColor">The color used used to fill the bitmap's background.</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
public static FIBITMAP Rotate<T>(FIBITMAP dib, double angle, T? backgroundColor) where T : struct
{
if (backgroundColor.HasValue)
{
GCHandle handle = new GCHandle();
try
{
T[] buffer = new T[] { backgroundColor.Value };
handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
return Rotate(dib, angle, handle.AddrOfPinnedObject());
}
finally
{
if (handle.IsAllocated)
handle.Free();
}
}
else
{
return Rotate(dib, angle, IntPtr.Zero);
}
}
/// <summary>
/// Rotates a 4-bit color FreeImage bitmap.
/// Allowed values for <paramref name="angle"/> are 90, 180 and 270.
/// In case <paramref name="angle"/> is 0 or 360 a clone is returned.
/// 0 is returned for other values or in case the rotation fails.
/// </summary>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <param name="angle">The angle of rotation.</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
/// <remarks>
/// This function is kind of temporary due to FreeImage's lack of
/// rotating 4-bit images. It's particularly used by <see cref="FreeImageBitmap"/>'s
/// method RotateFlip. This function will be removed as soon as FreeImage
/// supports rotating 4-bit images.
/// </remarks>
/// <exception cref="ArgumentNullException">
/// <paramref name="dib"/> is null.</exception>
public static unsafe FIBITMAP Rotate4bit(FIBITMAP dib, double angle)
{
if (dib.IsNull)
{
throw new ArgumentNullException("dib");
}
FIBITMAP result = new FIBITMAP();
int ang = (int)angle;
if ((GetImageType(dib) == FREE_IMAGE_TYPE.FIT_BITMAP) &&
(GetBPP(dib) == 4) &&
((ang % 90) == 0))
{
int width, height, xOrg, yOrg;
Scanline<FI4BIT>[] src, dst;
width = (int)GetWidth(dib);
height = (int)GetHeight(dib);
byte index = 0;
switch (ang)
{
case 90:
result = Allocate(height, width, 4, 0, 0, 0);
if (result.IsNull)
{
break;
}
CopyPalette(dib, result);
src = Get04BitScanlines(dib);
dst = Get04BitScanlines(result);
for (int y = 0; y < width; y++)
{
yOrg = height - 1;
for (int x = 0; x < height; x++, yOrg--)
{
index = src[yOrg][y];
dst[y][x] = index;
}
}
break;
case 180:
result = Allocate(width, height, 4, 0, 0, 0);
if (result.IsNull)
{
break;
}
CopyPalette(dib, result);
src = Get04BitScanlines(dib);
dst = Get04BitScanlines(result);
yOrg = height - 1;
for (int y = 0; y < height; y++, yOrg--)
{
xOrg = width - 1;
for (int x = 0; x < width; x++, xOrg--)
{
index = src[yOrg][xOrg];
dst[y][x] = index;
}
}
break;
case 270:
result = Allocate(height, width, 4, 0, 0, 0);
if (result.IsNull)
{
break;
}
CopyPalette(dib, result);
src = Get04BitScanlines(dib);
dst = Get04BitScanlines(result);
xOrg = width - 1;
for (int y = 0; y < width; y++, xOrg--)
{
for (int x = 0; x < height; x++)
{
index = src[x][xOrg];
dst[y][x] = index;
}
}
break;
case 0:
case 360:
result = Clone(dib);
break;
}
}
return result;
}
#endregion
#region Upsampling / downsampling
/// <summary>
/// Enlarges or shrinks the FreeImage bitmap selectively per side and fills newly added areas
/// with the specified background color. See remarks for further details.
/// </summary>
/// <typeparam name="T">The type of the specified color.</typeparam>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <param name="left">The number of pixels, the image should be enlarged on its left side.
/// Negative values shrink the image on its left side.</param>
/// <param name="top">The number of pixels, the image should be enlarged on its top side.
/// Negative values shrink the image on its top side.</param>
/// <param name="right">The number of pixels, the image should be enlarged on its right side.
/// Negative values shrink the image on its right side.</param>
/// <param name="bottom">The number of pixels, the image should be enlarged on its bottom side.
/// Negative values shrink the image on its bottom side.</param>
/// <param name="color">The color, the enlarged sides of the image should be filled with.</param>
/// <param name="options">Options that affect the color search process for palletized images.</param>
/// <returns>Handle to a FreeImage bitmap.</returns>
/// <remarks>
/// This function enlarges or shrinks an image selectively per side.
/// The main purpose of this function is to add borders to an image.
/// To add a border to any of the image's sides, a positive integer value must be passed in
/// any of the parameters <paramref name="left"/>, <paramref name="top"/>, <paramref name="right"/>
/// or <paramref name="bottom"/>. This value represents the border's
/// width in pixels. Newly created parts of the image (the border areas) are filled with the
/// specified <paramref name="color"/>.
/// Specifying a negative integer value for a certain side, will shrink or crop the image on
/// this side. Consequently, specifying zero for a certain side will not change the image's
/// extension on that side.
/// <para/>
/// So, calling this function with all parameters <paramref name="left"/>, <paramref name="top"/>,
/// <paramref name="right"/> and <paramref name="bottom"/> set to zero, is
/// effectively the same as calling function <see cref="Clone"/>; setting all parameters
/// <paramref name="left"/>, <paramref name="top"/>, <paramref name="right"/> and
/// <paramref name="bottom"/> to value equal to or smaller than zero, my easily be substituted
/// by a call to function <see cref="Copy"/>. Both these cases produce a new image, which is
/// guaranteed not to be larger than the input image. Thus, since the specified
/// <paramref name="color"/> is not needed in these cases, <paramref name="color"/>
/// may be <c>null</c>.
/// <para/>
/// Both parameters <paramref name="color"/> and <paramref name="options"/> work according to
/// function <see cref="FillBackground<T>"/>. So, please refer to the documentation of
/// <see cref="FillBackground<T>"/> to learn more about parameters <paramref name="color"/>
/// and <paramref name="options"/>. For palletized images, the palette of the input image is
/// transparently copied to the newly created enlarged or shrunken image, so any color look-ups
/// are performed on this palette.
/// </remarks>
/// <example>
/// // create a white color<br/>
/// RGBQUAD c;<br/>
/// c.rgbRed = 0xFF;<br/>
/// c.rgbGreen = 0xFF;<br/>
/// c.rgbBlue = 0xFF;<br/>
/// c.rgbReserved = 0x00;<br/>
/// <br/>
/// // add a white, symmetric 10 pixel wide border to the image<br/>
/// dib2 = FreeImage_EnlargeCanvas(dib, 10, 10, 10, 10, c, FREE_IMAGE_COLOR_OPTIONS.FICO_RGB);<br/>
/// <br/>
/// // add white, 20 pixel wide stripes to the top and bottom side of the image<br/>
/// dib3 = FreeImage_EnlargeCanvas(dib, 0, 20, 0, 20, c, FREE_IMAGE_COLOR_OPTIONS.FICO_RGB);<br/>
/// <br/>
/// // add white, 30 pixel wide stripes to the right side of the image and<br/>
/// // cut off the 40 leftmost pixel columns<br/>
/// dib3 = FreeImage_EnlargeCanvas(dib, -40, 0, 30, 0, c, FREE_IMAGE_COLOR_OPTIONS.FICO_RGB);<br/>
/// </example>
public static FIBITMAP EnlargeCanvas<T>(FIBITMAP dib, int left, int top, int right, int bottom,
T? color, FREE_IMAGE_COLOR_OPTIONS options) where T : struct
{
if (dib.IsNull)
return FIBITMAP.Zero;
if (color.HasValue)
{
if (!CheckColorType(GetImageType(dib), color.Value))
return FIBITMAP.Zero;
GCHandle handle = new GCHandle();
try
{
T[] buffer = new T[] { color.Value };
handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
return EnlargeCanvas(dib, left, top, right, bottom, handle.AddrOfPinnedObject(), options);
}
finally
{
if (handle.IsAllocated)
handle.Free();
}
}
else
{
return EnlargeCanvas(dib, left, top, right, bottom, IntPtr.Zero, options);
}
}
#endregion
#region Color
/// <summary>
/// Sets all pixels of the specified image to the color provided through the
/// <paramref name="color"/> parameter. See remarks for further details.
/// </summary>
/// <typeparam name="T">The type of the specified color.</typeparam>
/// <param name="dib">Handle to a FreeImage bitmap.</param>
/// <param name="color">The color to fill the bitmap with. See remarks for further details.</param>
/// <param name="options">Options that affect the color search process for palletized images.</param>
/// <returns><c>true</c> on success, <c>false</c> on failure.</returns>
/// <remarks>
/// This function sets all pixels of an image to the color provided through
/// the <paramref name="color"/> parameter. <see cref="RGBQUAD"/> is used for standard type images.
/// For non standard type images the underlaying structure is used.
/// <para/>
/// So, <paramref name="color"/> must be of type <see cref="Double"/>, if the image to be filled is of type
/// <see cref="FREE_IMAGE_TYPE.FIT_DOUBLE"/> and must be a <see cref="FIRGBF"/> structure if the
/// image is of type <see cref="FREE_IMAGE_TYPE.FIT_RGBF"/> and so on.
/// <para/>
/// However, the fill color is always specified through a <see cref="RGBQUAD"/> structure
/// for all images of type <see cref="FREE_IMAGE_TYPE.FIT_BITMAP"/>.
/// So, for 32- and 24-bit images, the red, green and blue members of the <see cref="RGBQUAD"/>
/// structure are directly used for the image's red, green and blue channel respectively.
/// Although alpha transparent <see cref="RGBQUAD"/> colors are
/// supported, the alpha channel of a 32-bit image never gets modified by this function.
/// A fill color with an alpha value smaller than 255 gets blended with the image's actual
/// background color, which is determined from the image's bottom-left pixel.
/// So, currently using alpha enabled colors, assumes the image to be unicolor before the
/// fill operation. However, the <see cref="RGBQUAD.rgbReserved"/> field is only taken into account,
/// if option <see cref="FREE_IMAGE_COLOR_OPTIONS.FICO_RGBA"/> has been specified.
/// <para/>
/// For 16-bit images, the red-, green- and blue components of the specified color are
/// transparently translated into either the 16-bit 555 or 565 representation. This depends
/// on the image's actual red- green- and blue masks.
/// <para/>
/// Special attention must be payed for palletized images. Generally, the RGB color specified
/// is looked up in the image's palette. The found palette index is then used to fill the image.
/// There are some option flags, that affect this lookup process:
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <description>Meaning</description>
/// </listheader>
/// <item>
/// <term><see cref="FREE_IMAGE_COLOR_OPTIONS.FICO_DEFAULT"/></term>
/// <description>
/// Uses the color, that is nearest to the specified color.
/// This is the default behavior and should always find a
/// color in the palette. However, the visual result may
/// far from what was expected and mainly depends on the
/// image's palette.
/// </description>
/// </item>
/// <item>
/// <term><see cref="FREE_IMAGE_COLOR_OPTIONS.FICO_EQUAL_COLOR"/></term>
/// <description>
/// Searches the image's palette for the specified color
/// but only uses the returned palette index, if the specified
/// color exactly matches the palette entry. Of course,
/// depending on the image's actual palette entries, this
/// operation may fail. In this case, the function falls back
/// to option <see cref="FREE_IMAGE_COLOR_OPTIONS.FICO_ALPHA_IS_INDEX"/>
/// and uses the RGBQUAD's rgbReserved member (or its low nibble for 4-bit images
/// or its least significant bit (LSB) for 1-bit images) as
/// the palette index used for the fill operation.
/// </description>
/// </item>
/// <item>
/// <term><see cref="FREE_IMAGE_COLOR_OPTIONS.FICO_ALPHA_IS_INDEX"/></term>
/// <description>
/// Does not perform any color lookup from the palette, but
/// uses the RGBQUAD's alpha channel member rgbReserved as
/// the palette index to be used for the fill operation.
/// However, for 4-bit images, only the low nibble of the
/// rgbReserved member are used and for 1-bit images, only
/// the least significant bit (LSB) is used.
/// </description>
/// </item>
/// </list>
/// </remarks>
public static bool FillBackground<T>(FIBITMAP dib, T color, FREE_IMAGE_COLOR_OPTIONS options)
where T : struct
{
if (dib.IsNull)
return false;
if (!CheckColorType(GetImageType(dib), color))
return false;
GCHandle handle = new GCHandle();
try
{
T[] buffer = new T[] { color };
handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
return FillBackground(dib, handle.AddrOfPinnedObject(), options);
}
finally
{
if (handle.IsAllocated)
handle.Free();
}
}
#endregion
#region Wrapper functions
/// <summary>
/// Returns the next higher possible color depth.
/// </summary>
/// <param name="bpp">Color depth to increase.</param>
/// <returns>The next higher color depth or 0 if there is no valid color depth.</returns>
internal static int GetNextColorDepth(int bpp)
{
int result = 0;
switch (bpp)
{
case 1:
result = 4;
break;
case 4:
result = 8;
break;
case 8:
result = 16;
break;
case 16:
result = 24;
break;
case 24:
result = 32;
break;
}
return result;
}
/// <summary>
/// Returns the next lower possible color depth.
/// </summary>
/// <param name="bpp">Color depth to decrease.</param>
/// <returns>The next lower color depth or 0 if there is no valid color depth.</returns>
internal static int GetPrevousColorDepth(int bpp)
{
int result = 0;
switch (bpp)
{
case 32:
result = 24;
break;
case 24:
result = 16;
break;
case 16:
result = 8;
break;
case 8:
result = 4;
break;
case 4:
result = 1;
break;
}
return result;
}
/// <summary>
/// Reads a null-terminated c-string.
/// </summary>
/// <param name="ptr">Pointer to the first char of the string.</param>
/// <returns>The converted string.</returns>
internal static unsafe string PtrToStr(byte* ptr)
{
string result = null;
if (ptr != null)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
while (*ptr != 0)
{
sb.Append((char)(*(ptr++)));
}
result = sb.ToString();
}
return result;
}
internal static unsafe byte[] CreateShrunkenPaletteLUT(FIBITMAP dib, out int uniqueColors)
{
byte[] result = null;
uniqueColors = 0;
if ((!dib.IsNull) && (GetImageType(dib) == FREE_IMAGE_TYPE.FIT_BITMAP) && (GetBPP(dib) <= 8))
{
int size = (int)GetColorsUsed(dib);
List<RGBQUAD> newPalette = new List<RGBQUAD>(size);
List<byte> lut = new List<byte>(size);
RGBQUAD* palette = (RGBQUAD*)GetPalette(dib);
RGBQUAD color;
int index;
for (int i = 0; i < size; i++)
{
color = palette[i];
color.rgbReserved = 255; // ignore alpha
index = newPalette.IndexOf(color);
if (index < 0)
{
newPalette.Add(color);
lut.Add((byte)(newPalette.Count - 1));
}
else
{
lut.Add((byte)index);
}
}
result = lut.ToArray();
uniqueColors = newPalette.Count;
}
return result;
}
internal static PropertyItem CreatePropertyItem()
{
return (PropertyItem)Activator.CreateInstance(typeof(PropertyItem), true);
}
private static unsafe void CopyPalette(FIBITMAP src, FIBITMAP dst)
{
RGBQUAD* orgPal = (RGBQUAD*)GetPalette(src);
RGBQUAD* newPal = (RGBQUAD*)GetPalette(dst);
uint size = (uint)(sizeof(RGBQUAD) * GetColorsUsed(src));
CopyMemory(newPal, orgPal, size);
}
private static unsafe Scanline<FI4BIT>[] Get04BitScanlines(FIBITMAP dib)
{
int height = (int)GetHeight(dib);
Scanline<FI4BIT>[] array = new Scanline<FI4BIT>[height];
for (int i = 0; i < height; i++)
{
array[i] = new Scanline<FI4BIT>(dib, i);
}
return array;
}
/// <summary>
/// Changes a bitmaps color depth.
/// Used by SaveEx and SaveToStream.
/// </summary>
private static FIBITMAP PrepareBitmapColorDepth(FIBITMAP dibToSave, FREE_IMAGE_FORMAT format, FREE_IMAGE_COLOR_DEPTH colorDepth)
{
FREE_IMAGE_TYPE type = GetImageType(dibToSave);
if (type == FREE_IMAGE_TYPE.FIT_BITMAP)
{
int bpp = (int)GetBPP(dibToSave);
int targetBpp = (int)(colorDepth & FREE_IMAGE_COLOR_DEPTH.FICD_COLOR_MASK);
if (colorDepth != FREE_IMAGE_COLOR_DEPTH.FICD_AUTO)
{
// A fix colordepth was chosen
if (FIFSupportsExportBPP(format, targetBpp))
{
dibToSave = ConvertColorDepth(dibToSave, colorDepth, false);
}
else
{
throw new ArgumentException("FreeImage\n\nFreeImage Library plugin " +
GetFormatFromFIF(format) + " is unable to write images with a color depth of " +
targetBpp + " bpp.");
}
}
else
{
// Auto selection was chosen
if (!FIFSupportsExportBPP(format, bpp))
{
// The color depth is not supported
int bppUpper = bpp;
int bppLower = bpp;
// Check from the bitmaps current color depth in both directions
do
{
bppUpper = GetNextColorDepth(bppUpper);
if (FIFSupportsExportBPP(format, bppUpper))
{
dibToSave = ConvertColorDepth(dibToSave, (FREE_IMAGE_COLOR_DEPTH)bppUpper, false);
break;
}
bppLower = GetPrevousColorDepth(bppLower);
if (FIFSupportsExportBPP(format, bppLower))
{
dibToSave = ConvertColorDepth(dibToSave, (FREE_IMAGE_COLOR_DEPTH)bppLower, false);
break;
}
} while (!((bppLower == 0) && (bppUpper == 0)));
}
}
}
return dibToSave;
}
/// <summary>
/// Compares blocks of memory.
/// </summary>
/// <param name="buf1">A pointer to a block of memory to compare.</param>
/// <param name="buf2">A pointer to a block of memory to compare.</param>
/// <param name="length">Specifies the number of bytes to be compared.</param>
/// <returns>true, if all bytes compare as equal, false otherwise.</returns>
public static unsafe bool CompareMemory(void* buf1, void* buf2, uint length)
{
return (length == RtlCompareMemory(buf1, buf2, length));
}
/// <summary>
/// Compares blocks of memory.
/// </summary>
/// <param name="buf1">A pointer to a block of memory to compare.</param>
/// <param name="buf2">A pointer to a block of memory to compare.</param>
/// <param name="length">Specifies the number of bytes to be compared.</param>
/// <returns>true, if all bytes compare as equal, false otherwise.</returns>
public static unsafe bool CompareMemory(void* buf1, void* buf2, long length)
{
return (length == RtlCompareMemory(buf1, buf2, checked((uint)length)));
}
/// <summary>
/// Compares blocks of memory.
/// </summary>
/// <param name="buf1">A pointer to a block of memory to compare.</param>
/// <param name="buf2">A pointer to a block of memory to compare.</param>
/// <param name="length">Specifies the number of bytes to be compared.</param>
/// <returns>true, if all bytes compare as equal, false otherwise.</returns>
public static unsafe bool CompareMemory(IntPtr buf1, IntPtr buf2, uint length)
{
return (length == RtlCompareMemory(buf1.ToPointer(), buf2.ToPointer(), length));
}
/// <summary>
/// Compares blocks of memory.
/// </summary>
/// <param name="buf1">A pointer to a block of memory to compare.</param>
/// <param name="buf2">A pointer to a block of memory to compare.</param>
/// <param name="length">Specifies the number of bytes to be compared.</param>
/// <returns>true, if all bytes compare as equal, false otherwise.</returns>
public static unsafe bool CompareMemory(IntPtr buf1, IntPtr buf2, long length)
{
return (length == RtlCompareMemory(buf1.ToPointer(), buf2.ToPointer(), checked((uint)length)));
}
/// <summary>
/// Moves a block of memory from one location to another.
/// </summary>
/// <param name="dst">A pointer to the starting address of the move destination.</param>
/// <param name="src">A pointer to the starting address of the block of memory to be moved.</param>
/// <param name="size">The size of the block of memory to move, in bytes.</param>
public static unsafe void MoveMemory(void* dst, void* src, long size)
{
MoveMemory(dst, src, checked((uint)size));
}
/// <summary>
/// Moves a block of memory from one location to another.
/// </summary>
/// <param name="dst">A pointer to the starting address of the move destination.</param>
/// <param name="src">A pointer to the starting address of the block of memory to be moved.</param>
/// <param name="size">The size of the block of memory to move, in bytes.</param>
public static unsafe void MoveMemory(IntPtr dst, IntPtr src, uint size)
{
MoveMemory(dst.ToPointer(), src.ToPointer(), size);
}
/// <summary>
/// Moves a block of memory from one location to another.
/// </summary>
/// <param name="dst">A pointer to the starting address of the move destination.</param>
/// <param name="src">A pointer to the starting address of the block of memory to be moved.</param>
/// <param name="size">The size of the block of memory to move, in bytes.</param>
public static unsafe void MoveMemory(IntPtr dst, IntPtr src, long size)
{
MoveMemory(dst.ToPointer(), src.ToPointer(), checked((uint)size));
}
/// <summary>
/// Copies a block of memory from one location to another.
/// </summary>
/// <param name="dest">A pointer to the starting address of the copied block's destination.</param>
/// <param name="src">A pointer to the starting address of the block of memory to copy.</param>
/// <param name="len">The size of the block of memory to copy, in bytes.</param>
/// <remarks>
/// <b>CopyMemory</b> runs faster than <see cref="MoveMemory(void*, void*, uint)"/>.
/// However, if both blocks overlap the result is undefined.
/// </remarks>
public static unsafe void CopyMemory(byte* dest, byte* src, int len)
{
if (len >= 0x10)
{
do
{
*((int*)dest) = *((int*)src);
*((int*)(dest + 4)) = *((int*)(src + 4));
*((int*)(dest + 8)) = *((int*)(src + 8));
*((int*)(dest + 12)) = *((int*)(src + 12));
dest += 0x10;
src += 0x10;
}
while ((len -= 0x10) >= 0x10);
}
if (len > 0)
{
if ((len & 8) != 0)
{
*((int*)dest) = *((int*)src);
*((int*)(dest + 4)) = *((int*)(src + 4));
dest += 8;
src += 8;
}
if ((len & 4) != 0)
{
*((int*)dest) = *((int*)src);
dest += 4;
src += 4;
}
if ((len & 2) != 0)
{
*((short*)dest) = *((short*)src);
dest += 2;
src += 2;
}
if ((len & 1) != 0)
{
*dest = *src;
}
}
}
/// <summary>
/// Copies a block of memory from one location to another.
/// </summary>
/// <param name="dest">A pointer to the starting address of the copied block's destination.</param>
/// <param name="src">A pointer to the starting address of the block of memory to copy.</param>
/// <param name="len">The size of the block of memory to copy, in bytes.</param>
/// <remarks>
/// <b>CopyMemory</b> runs faster than <see cref="MoveMemory(void*, void*, long)"/>.
/// However, if both blocks overlap the result is undefined.
/// </remarks>
public static unsafe void CopyMemory(byte* dest, byte* src, long len)
{
CopyMemory(dest, src, checked((int)len));
}
/// <summary>
/// Copies a block of memory from one location to another.
/// </summary>
/// <param name="dest">A pointer to the starting address of the copied block's destination.</param>
/// <param name="src">A pointer to the starting address of the block of memory to copy.</param>
/// <param name="len">The size of the block of memory to copy, in bytes.</param>
/// <remarks>
/// <b>CopyMemory</b> runs faster than <see cref="MoveMemory(void*, void*, long)"/>.
/// However, if both blocks overlap the result is undefined.
/// </remarks>
public static unsafe void CopyMemory(void* dest, void* src, long len)
{
CopyMemory((byte*)dest, (byte*)src, checked((int)len));
}
/// <summary>
/// Copies a block of memory from one location to another.
/// </summary>
/// <param name="dest">A pointer to the starting address of the copied block's destination.</param>
/// <param name="src">A pointer to the starting address of the block of memory to copy.</param>
/// <param name="len">The size of the block of memory to copy, in bytes.</param>
/// <remarks>
/// <b>CopyMemory</b> runs faster than <see cref="MoveMemory(void*, void*, uint)"/>.
/// However, if both blocks overlap the result is undefined.
/// </remarks>
public static unsafe void CopyMemory(void* dest, void* src, int len)
{
CopyMemory((byte*)dest, (byte*)src, len);
}
/// <summary>
/// Copies a block of memory from one location to another.
/// </summary>
/// <param name="dest">A pointer to the starting address of the copied block's destination.</param>
/// <param name="src">A pointer to the starting address of the block of memory to copy.</param>
/// <param name="len">The size of the block of memory to copy, in bytes.</param>
/// <remarks>
/// <b>CopyMemory</b> runs faster than <see cref="MoveMemory(IntPtr, IntPtr, uint)"/>.
/// However, if both blocks overlap the result is undefined.
/// </remarks>
public static unsafe void CopyMemory(IntPtr dest, IntPtr src, int len)
{
CopyMemory((byte*)dest, (byte*)src, len);
}
/// <summary>
/// Copies a block of memory from one location to another.
/// </summary>
/// <param name="dest">A pointer to the starting address of the copied block's destination.</param>
/// <param name="src">A pointer to the starting address of the block of memory to copy.</param>
/// <param name="len">The size of the block of memory to copy, in bytes.</param>
/// <remarks>
/// <b>CopyMemory</b> runs faster than <see cref="MoveMemory(IntPtr, IntPtr, long)"/>.
/// However, if both blocks overlap the result is undefined.
/// </remarks>
public static unsafe void CopyMemory(IntPtr dest, IntPtr src, long len)
{
CopyMemory((byte*)dest, (byte*)src, checked((int)len));
}
/// <summary>
/// Copies a block of memory into an array.
/// </summary>
/// <param name="dest">An array used as the destination of the copy process.</param>
/// <param name="src">A pointer to the starting address of the block of memory to copy.</param>
/// <param name="len">The size of the block of memory to copy, in bytes.</param>
public static unsafe void CopyMemory(Array dest, void* src, int len)
{
GCHandle handle = GCHandle.Alloc(dest, GCHandleType.Pinned);
try
{
CopyMemory((byte*)handle.AddrOfPinnedObject(), (byte*)src, len);
}
finally
{
handle.Free();
}
}
/// <summary>
/// Copies a block of memory into an array.
/// </summary>
/// <param name="dest">An array used as the destination of the copy process.</param>
/// <param name="src">A pointer to the starting address of the block of memory to copy.</param>
/// <param name="len">The size of the block of memory to copy, in bytes.</param>
public static unsafe void CopyMemory(Array dest, void* src, long len)
{
CopyMemory(dest, (byte*)src, checked((int)len));
}
/// <summary>
/// Copies a block of memory into an array.
/// </summary>
/// <param name="dest">An array used as the destination of the copy process.</param>
/// <param name="src">A pointer to the starting address of the block of memory to copy.</param>
/// <param name="len">The size of the block of memory to copy, in bytes.</param>
public static unsafe void CopyMemory(Array dest, IntPtr src, int len)
{
CopyMemory(dest, (byte*)src, len);
}
/// <summary>
/// Copies a block of memory into an array.
/// </summary>
/// <param name="dest">An array used as the destination of the copy process.</param>
/// <param name="src">A pointer to the starting address of the block of memory to copy.</param>
/// <param name="len">The size of the block of memory to copy, in bytes.</param>
public static unsafe void CopyMemory(Array dest, IntPtr src, long len)
{
CopyMemory(dest, (byte*)src, checked((int)len));
}
/// <summary>
/// Copies the content of an array to a memory location.
/// </summary>
/// <param name="dest">A pointer to the starting address of the copied block's destination.</param>
/// <param name="src">An array used as the source of the copy process.</param>
/// <param name="len">The size of the block of memory to copy, in bytes.</param>
public static unsafe void CopyMemory(void* dest, Array src, int len)
{
GCHandle handle = GCHandle.Alloc(src, GCHandleType.Pinned);
try
{
CopyMemory((byte*)dest, (byte*)handle.AddrOfPinnedObject(), len);
}
finally
{
handle.Free();
}
}
/// <summary>
/// Copies the content of an array to a memory location.
/// </summary>
/// <param name="dest">A pointer to the starting address of the copied block's destination.</param>
/// <param name="src">An array used as the source of the copy process.</param>
/// <param name="len">The size of the block of memory to copy, in bytes.</param>
public static unsafe void CopyMemory(void* dest, Array src, long len)
{
CopyMemory((byte*)dest, src, checked((int)len));
}
/// <summary>
/// Copies the content of an array to a memory location.
/// </summary>
/// <param name="dest">A pointer to the starting address of the copied block's destination.</param>
/// <param name="src">An array used as the source of the copy process.</param>
/// <param name="len">The size of the block of memory to copy, in bytes.</param>
public static unsafe void CopyMemory(IntPtr dest, Array src, int len)
{
CopyMemory((byte*)dest, src, len);
}
/// <summary>
/// Copies the content of an array to a memory location.
/// </summary>
/// <param name="dest">A pointer to the starting address of the copied block's destination.</param>
/// <param name="src">An array used as the source of the copy process.</param>
/// <param name="len">The size of the block of memory to copy, in bytes.</param>
public static unsafe void CopyMemory(IntPtr dest, Array src, long len)
{
CopyMemory((byte*)dest, src, checked((int)len));
}
/// <summary>
/// Copies the content of one array into another array.
/// </summary>
/// <param name="dest">An array used as the destination of the copy process.</param>
/// <param name="src">An array used as the source of the copy process.</param>
/// <param name="len">The size of the content to copy, in bytes.</param>
public static unsafe void CopyMemory(Array dest, Array src, int len)
{
GCHandle dHandle = GCHandle.Alloc(dest, GCHandleType.Pinned);
try
{
GCHandle sHandle = GCHandle.Alloc(src, GCHandleType.Pinned);
try
{
CopyMemory((byte*)dHandle.AddrOfPinnedObject(), (byte*)sHandle.AddrOfPinnedObject(), len);
}
finally
{
sHandle.Free();
}
}
finally
{
dHandle.Free();
}
}
/// <summary>
/// Copies the content of one array into another array.
/// </summary>
/// <param name="dest">An array used as the destination of the copy process.</param>
/// <param name="src">An array used as the source of the copy process.</param>
/// <param name="len">The size of the content to copy, in bytes.</param>
public static unsafe void CopyMemory(Array dest, Array src, long len)
{
CopyMemory(dest, src, checked((int)len));
}
internal static string ColorToString(Color color)
{
return string.Format(
System.Globalization.CultureInfo.CurrentCulture,
"{{Name={0}, ARGB=({1}, {2}, {3}, {4})}}",
new object[] { color.Name, color.A, color.R, color.G, color.B });
}
internal static void Resize(ref string str, int length)
{
if ((str != null) && (length >= 0) && (str.Length != length))
{
char[] chars = str.ToCharArray();
Array.Resize(ref chars, length);
str = new string(chars);
}
}
internal static void Resize(ref string str, int min, int max)
{
if ((str != null) && (min >= 0) && (max >= 0) && (min <= max))
{
if (str.Length < min)
{
char[] chars = str.ToCharArray();
Array.Resize(ref chars, min);
str = new string(chars);
}
else if (str.Length > max)
{
char[] chars = str.ToCharArray();
Array.Resize(ref chars, max);
str = new string(chars);
}
}
}
internal static void Resize<T>(ref T[] array, int length)
{
if ((array != null) && (length >= 0) && (array.Length != length))
{
Array.Resize(ref array, length);
}
}
internal static void Resize<T>(ref T[] array, int min, int max)
{
if ((array != null) && (min >= 0) && (max >= 0) && (min <= max))
{
if (array.Length < min)
{
Array.Resize(ref array, min);
}
else if (array.Length > max)
{
Array.Resize(ref array, max);
}
}
}
internal static bool CheckColorType<T>(FREE_IMAGE_TYPE imageType, T color)
{
Type type = typeof(T);
bool result;
switch (imageType)
{
case FREE_IMAGE_TYPE.FIT_BITMAP:
result = (type == typeof(RGBQUAD)); break;
case FREE_IMAGE_TYPE.FIT_COMPLEX:
result = (type == typeof(FICOMPLEX)); break;
case FREE_IMAGE_TYPE.FIT_DOUBLE:
result = (type == typeof(double)); break;
case FREE_IMAGE_TYPE.FIT_FLOAT:
result = (type == typeof(float)); break;
case FREE_IMAGE_TYPE.FIT_INT16:
result = (type == typeof(Int16)); break;
case FREE_IMAGE_TYPE.FIT_INT32:
result = (type == typeof(Int32)); break;
case FREE_IMAGE_TYPE.FIT_RGB16:
result = (type == typeof(FIRGB16)); break;
case FREE_IMAGE_TYPE.FIT_RGBA16:
result = (type == typeof(FIRGBA16)); break;
case FREE_IMAGE_TYPE.FIT_RGBAF:
result = (type == typeof(FIRGBAF)); break;
case FREE_IMAGE_TYPE.FIT_RGBF:
result = (type == typeof(FIRGBF)); break;
case FREE_IMAGE_TYPE.FIT_UINT16:
result = (type == typeof(UInt16)); break;
case FREE_IMAGE_TYPE.FIT_UINT32:
result = (type == typeof(UInt32)); break;
default:
result = false; break;
}
return result;
}
#endregion
#region Dll-Imports
/// <summary>
/// Retrieves a handle to a display device context (DC) for the client area of a specified window
/// or for the entire screen. You can use the returned handle in subsequent GDI functions to draw in the DC.
/// </summary>
/// <param name="hWnd">Handle to the window whose DC is to be retrieved.
/// If this value is IntPtr.Zero, GetDC retrieves the DC for the entire screen. </param>
/// <returns>If the function succeeds, the return value is a handle to the DC for the specified window's client area.
/// If the function fails, the return value is NULL.</returns>
[DllImport("user32.dll")]
private static extern IntPtr GetDC(IntPtr hWnd);
/// <summary>
/// Releases a device context (DC), freeing it for use by other applications.
/// The effect of the ReleaseDC function depends on the type of DC. It frees only common and window DCs.
/// It has no effect on class or private DCs.
/// </summary>
/// <param name="hWnd">Handle to the window whose DC is to be released.</param>
/// <param name="hDC">Handle to the DC to be released.</param>
/// <returns>Returns true on success, false on failure.</returns>
[DllImport("user32.dll")]
private static extern bool ReleaseDC(IntPtr hWnd, IntPtr hDC);
/// <summary>
/// Creates a DIB that applications can write to directly.
/// The function gives you a pointer to the location of the bitmap bit values.
/// You can supply a handle to a file-mapping object that the function will use to create the bitmap,
/// or you can let the system allocate the memory for the bitmap.
/// </summary>
/// <param name="hdc">Handle to a device context.</param>
/// <param name="pbmi">Pointer to a BITMAPINFO structure that specifies various attributes of the DIB,
/// including the bitmap dimensions and colors.</param>
/// <param name="iUsage">Specifies the type of data contained in the bmiColors array member of the BITMAPINFO structure
/// pointed to by pbmi (either logical palette indexes or literal RGB values).</param>
/// <param name="ppvBits">Pointer to a variable that receives a pointer to the location of the DIB bit values.</param>
/// <param name="hSection">Handle to a file-mapping object that the function will use to create the DIB.
/// This parameter can be NULL.</param>
/// <param name="dwOffset">Specifies the offset from the beginning of the file-mapping object referenced by hSection
/// where storage for the bitmap bit values is to begin. This value is ignored if hSection is NULL.</param>
/// <returns>If the function succeeds, the return value is a handle to the newly created DIB,
/// and *ppvBits points to the bitmap bit values. If the function fails, the return value is NULL, and *ppvBits is NULL.</returns>
[DllImport("gdi32.dll")]
private static extern IntPtr CreateDIBSection(
IntPtr hdc,
[In] IntPtr pbmi,
uint iUsage,
out IntPtr ppvBits,
IntPtr hSection,
uint dwOffset);
/// <summary>
/// Deletes a logical pen, brush, font, bitmap, region, or palette, freeing all system resources associated with the object.
/// After the object is deleted, the specified handle is no longer valid.
/// </summary>
/// <param name="hObject">Handle to a logical pen, brush, font, bitmap, region, or palette.</param>
/// <returns>Returns true on success, false on failure.</returns>
[DllImport("gdi32.dll")]
private static extern bool DeleteObject(IntPtr hObject);
/// <summary>
/// Creates a compatible bitmap (DDB) from a DIB and, optionally, sets the bitmap bits.
/// </summary>
/// <param name="hdc">Handle to a device context.</param>
/// <param name="lpbmih">Pointer to a bitmap information header structure.</param>
/// <param name="fdwInit">Specifies how the system initializes the bitmap bits - (use 4).</param>
/// <param name="lpbInit">Pointer to an array of bytes containing the initial bitmap data.</param>
/// <param name="lpbmi">Pointer to a BITMAPINFO structure that describes the dimensions
/// and color format of the array pointed to by the lpbInit parameter.</param>
/// <param name="fuUsage">Specifies whether the bmiColors member of the BITMAPINFO structure
/// was initialized - (use 0).</param>
/// <returns>Handle to a DIB or null on failure.</returns>
[DllImport("gdi32.dll")]
private static extern IntPtr CreateDIBitmap(
IntPtr hdc,
IntPtr lpbmih,
uint fdwInit,
IntPtr lpbInit,
IntPtr lpbmi,
uint fuUsage);
/// <summary>
/// Retrieves information for the specified graphics object.
/// </summary>
/// <param name="hgdiobj">Handle to the graphics object of interest.</param>
/// <param name="cbBuffer">Specifies the number of bytes of information to
/// be written to the buffer.</param>
/// <param name="lpvObject">Pointer to a buffer that receives the information
/// about the specified graphics object.</param>
/// <returns>0 on failure.</returns>
[DllImport("gdi32.dll")]
private static extern int GetObject(IntPtr hgdiobj, int cbBuffer, IntPtr lpvObject);
/// <summary>
/// Retrieves the bits of the specified compatible bitmap and copies them into a buffer
/// as a DIB using the specified format.
/// </summary>
/// <param name="hdc">Handle to the device context.</param>
/// <param name="hbmp">Handle to the bitmap. This must be a compatible bitmap (DDB).</param>
/// <param name="uStartScan">Specifies the first scan line to retrieve.</param>
/// <param name="cScanLines">Specifies the number of scan lines to retrieve.</param>
/// <param name="lpvBits">Pointer to a buffer to receive the bitmap data.</param>
/// <param name="lpbmi">Pointer to a BITMAPINFO structure that specifies the desired
/// format for the DIB data.</param>
/// <param name="uUsage">Specifies the format of the bmiColors member of the
/// BITMAPINFO structure - (use 0).</param>
/// <returns>0 on failure.</returns>
[DllImport("gdi32.dll")]
private static extern unsafe int GetDIBits(
IntPtr hdc,
IntPtr hbmp,
uint uStartScan,
uint cScanLines,
IntPtr lpvBits,
IntPtr lpbmi,
uint uUsage);
/// <summary>
/// Moves a block of memory from one location to another.
/// </summary>
/// <param name="dst">Pointer to the starting address of the move destination.</param>
/// <param name="src">Pointer to the starting address of the block of memory to be moved.</param>
/// <param name="size">Size of the block of memory to move, in bytes.</param>
[DllImport("Kernel32.dll", EntryPoint = "RtlMoveMemory", SetLastError = false)]
public static unsafe extern void MoveMemory(void* dst, void* src, uint size);
/// <summary>
/// The RtlCompareMemory routine compares blocks of memory
/// and returns the number of bytes that are equivalent.
/// </summary>
/// <param name="buf1">A pointer to a block of memory to compare.</param>
/// <param name="buf2">A pointer to a block of memory to compare.</param>
/// <param name="count">Specifies the number of bytes to be compared.</param>
/// <returns>RtlCompareMemory returns the number of bytes that compare as equal.
/// If all bytes compare as equal, the input Length is returned.</returns>
[DllImport("ntdll.dll", EntryPoint = "RtlCompareMemory", SetLastError = false)]
internal static unsafe extern uint RtlCompareMemory(void* buf1, void* buf2, uint count);
#endregion
}
}
|