File: class.t3lib_stdgraphic.php

package info (click to toggle)
typo3-src 4.0.2%2Bdebian-3
  • links: PTS
  • area: main
  • in suites: etch-m68k
  • size: 29,856 kB
  • ctags: 33,382
  • sloc: php: 134,523; xml: 6,976; sql: 1,084; sh: 168; makefile: 45
file content (2955 lines) | stat: -rw-r--r-- 102,203 bytes parent folder | download | duplicates (2)
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
<?php
/***************************************************************
*  Copyright notice
*
*  (c) 1999-2006 Kasper Skaarhoj (kasperYYYY@typo3.com)
*  All rights reserved
*
*  This script is part of the TYPO3 project. The TYPO3 project is
*  free software; you can redistribute it and/or modify
*  it under the terms of the GNU General Public License as published by
*  the Free Software Foundation; either version 2 of the License, or
*  (at your option) any later version.
*
*  The GNU General Public License can be found at
*  http://www.gnu.org/copyleft/gpl.html.
*  A copy is found in the textfile GPL.txt and important notices to the license
*  from the author is found in LICENSE.txt distributed with these scripts.
*
*
*  This script is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU General Public License for more details.
*
*  This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
/**
 * Standard graphical functions
 *
 * $Id: class.t3lib_stdgraphic.php 1657 2006-07-26 17:54:15Z mundaun $
 * Revised for TYPO3 3.6 July/2003 by Kasper Skaarhoj
 *
 * @author	Kasper Skaarhoj <kasperYYYY@typo3.com>
 */
/**
 * [CLASS/FUNCTION INDEX of SCRIPT]
 *
 *
 *
 *  155: class t3lib_stdGraphic
 *  236:     function init()
 *
 *              SECTION: Layering images / "IMAGE" GIFBUILDER object
 *  366:     function maskImageOntoImage(&$im,$conf,$workArea)
 *  436:     function copyImageOntoImage(&$im,$conf,$workArea)
 *  458:     function copyGifOntoGif(&$im,$cpImg,$conf,$workArea)
 *  537:     function imagecopyresized(&$im, $cpImg, $Xstart, $Ystart, $cpImgCutX, $cpImgCutY, $w, $h, $w, $h)
 *
 *              SECTION: Text / "TEXT" GIFBUILDER object
 *  587:     function makeText(&$im,$conf,$workArea)
 *  707:     function txtPosition($conf,$workArea,$BB)
 *  761:     function calcBBox($conf)
 *  820:     function addToMap($cords,$conf)
 *  843:     function calcTextCordsForMap($cords,$offset, $conf)
 *  878:     function SpacedImageTTFText(&$im, $fontSize, $angle, $x, $y, $Fcolor, $fontFile, $text, $spacing, $wordSpacing, $splitRenderingConf, $sF=1)
 *  915:     function fontResize($conf)
 *  958:     function ImageTTFBBoxWrapper($fontSize, $angle, $fontFile, $string, $splitRendering, $sF=1)
 * 1005:     function ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $color, $fontFile, $string, $splitRendering,$sF=1)
 * 1058:     function splitString($string,$splitRendering,$fontSize,$fontFile)
 * 1208:     function calcWordSpacing($conf, $scaleFactor=1)
 * 1227:     function getTextScalFactor($conf)
 *
 *              SECTION: Other GIFBUILDER objects related to TEXT
 * 1262:     function makeOutline(&$im,$conf,$workArea,$txtConf)
 * 1291:     function circleOffset($distance, $iterations)
 * 1315:     function makeEmboss(&$im,$conf,$workArea,$txtConf)
 * 1337:     function makeShadow(&$im,$conf,$workArea,$txtConf)
 *
 *              SECTION: Other GIFBUILDER objects
 * 1469:     function makeBox(&$im,$conf,$workArea)
 * 1491:     function makeEffect(&$im, $conf)
 * 1506:     function IMparams($setup)
 * 1589:     function adjust(&$im, $conf)
 * 1621:     function crop(&$im,$conf)
 * 1652:     function scale(&$im,$conf)
 * 1684:     function setWorkArea($workArea)
 *
 *              SECTION: Adjustment functions
 * 1725:     function autolevels(&$im)
 * 1756:     function outputLevels(&$im,$low,$high,$swap='')
 * 1788:     function inputLevels(&$im,$low,$high,$swap='')
 * 1819:     function reduceColors(&$im,$limit, $cols)
 * 1832:     function IMreduceColors($file, $cols)
 *
 *              SECTION: GIFBUILDER Helper functions
 * 1875:     function prependAbsolutePath($fontFile)
 * 1889:     function v5_sharpen($factor)
 * 1908:     function v5_blur($factor)
 * 1925:     function randomName()
 * 1938:     function applyOffset($cords,$OFFSET)
 * 1951:     function convertColor($string)
 * 2001:     function recodeString($string)
 * 2023:     function singleChars($theText,$returnUnicodeNumber=FALSE)
 * 2046:     function objPosition($conf,$workArea,$BB)
 *
 *              SECTION: Scaling, Dimensions of images
 * 2125:     function imageMagickConvert($imagefile,$newExt='',$w='',$h='',$params='',$frame='',$options='',$mustCreate=0)
 * 2238:     function getImageDimensions($imageFile)
 * 2266:     function cacheImageDimensions($identifyResult)
 * 2298:     function getCachedImageDimensions($imageFile)
 * 2332:     function getImageScale($info,$w,$h,$options)
 * 2438:     function file_exists_typo3temp_file($output,$orig='')
 *
 *              SECTION: ImageMagick API functions
 * 2499:     function imageMagickIdentify($imagefile)
 * 2534:     function imageMagickExec($input,$output,$params)
 * 2557:     function combineExec($input,$overlay,$mask,$output, $handleNegation = false)
 * 2588:     function wrapFileName($inputName)
 *
 *              SECTION: Various IO functions
 * 2629:     function checkFile($file)
 * 2643:     function createTempSubDir($dirName)
 * 2665:     function applyImageMagickToPHPGif(&$im, $command)
 * 2691:     function gif_or_jpg($type,$w,$h)
 * 2708:     function output($file)
 * 2748:     function destroy()
 * 2758:     function imgTag ($imgInfo)
 * 2770:     function ImageWrite($destImg, $theImage)
 * 2808:     function imageGif($destImg, $theImage)
 * 2820:     function imageCreateFromGif($sourceImg)
 * 2831:     function imageCreateFromFile($sourceImg)
 * 2870:     function imagecreate($w, $h)
 * 2885:     function hexColor($col)
 * 2903:     function unifyColors(&$img, $colArr, $closest = false)
 *
 * TOTAL FUNCTIONS: 66
 * (This index is automatically created/updated by the extension "extdeveval")
 *
 */
















/**
 * Class contains a bunch of cool functions for manipulating graphics with GDlib/Freetype and ImageMagick
 * VERY OFTEN used with gifbuilder that extends this class and provides a TypoScript API to using these functions
 *
 * @author	Kasper Skaarhoj <kasperYYYY@typo3.com>
 * @package TYPO3
 * @subpackage t3lib
 * @see tslib_gifBuilder
 */
class t3lib_stdGraphic	{

		// Internal configuration, set in init()
	var $combineScript = 'combine';				// The ImageMagick filename used for combining two images. This name changed during the versions.
	var $noFramePrepended=0;					// If set, there is no frame pointer prepended to the filenames.
	var $GD2=0;									// Set, if the GDlib used is version 2.
	var $imagecopyresized_fix=0;				// If set, imagecopyresized will not be called directly. For GD2 (some PHP installs?)
	var $gifExtension = 'gif';					// This should be changed to 'png' if you want this class to read/make PNG-files instead!
	var $gdlibExtensions = '';			// File formats supported by gdlib. This variable get's filled in "init" method
	var $truecolor = true;					// Internal variable which get's used to determine wheter GDlib should use function truecolor pendants
	var $png_truecolor = false;					// Set to true if generated png's should be truecolor by default
	var $truecolorColors = 0xffffff;			// 16777216 Colors is the maximum value for PNG, JPEG truecolor images (24-bit, 8-bit / Channel)
	var $TTFLocaleConv = '';					// Used to recode input to TTF-functions for other charsets.
	var $enable_typo3temp_db_tracking = 0;		// If set, then all files in typo3temp will be logged in a database table. In addition to being a log of the files with original filenames, it also serves to secure that the same image is not rendered simultaneously by two different processes.
	var $imageFileExt = 'gif,jpg,jpeg,png,tif,bmp,tga,pcx,ai,pdf';	// Commalist of file extensions perceived as images by TYPO3. List should be set to 'gif,png,jpeg,jpg' if IM is not available. Lowercase and no spaces between!
	var $webImageExt = 'gif,jpg,jpeg,png';		// Commalist of web image extensions (can be shown by a webbrowser)
	var $maskNegate = '';						// Will be ' -negate' if ImageMagick ver 5.2+. See init();
	var $NO_IM_EFFECTS = '';
	var $cmds = Array (
		'jpg' => '',
		'jpeg' => '',
		'gif' => '-colors 64',
		'png' => '-colors 64'
	);
	var $NO_IMAGE_MAGICK = '';
	var $V5_EFFECTS = 0;
	var $im_version_4 = 0;
	var $mayScaleUp = 1;

		// Variables for testing, alternative usage etc.
	var $filenamePrefix='';								// Filename prefix for images scaled in imageMagickConvert()
	var $imageMagickConvert_forceFileNameBody='';		// Forcing the output filename of imageMagickConvert() to this value. However after calling imageMagickConvert() it will be set blank again.
	var $dontCheckForExistingTempFile = 0;				// This flag should always be false. If set true, imageMagickConvert will always write a new file to the tempdir! Used for debugging.
	var $dontCompress=0;								// Prevents imageMagickConvert() from compressing the gif-files with t3lib_div::gif_compress()
	var $dontUnlinkTempFiles=0;							// For debugging ONLY!
	var $alternativeOutputKey='';						// For debugging only. Filenames will not be based on mtime and only filename (not path) will be used. This key is also included in the hash of the filename...

		// Internal:
	var $IM_commands = Array();							// All ImageMagick commands executed is stored in this array for tracking. Used by the Install Tools Image section
	var $workArea = Array();

		// Constants:
	var $tempPath = 'typo3temp/';						// The temp-directory where to store the files. Normally relative to PATH_site but is allowed to be the absolute path AS LONG AS it is a subdir to PATH_site.
	var $absPrefix = '';								// Prefix for relative paths. Used in "show_item.php" script. Is prefixed the output file name IN imageMagickConvert()
	var $scalecmd = '-geometry';						// ImageMagick scaling command; "-geometry" eller "-sample". Used in makeText() and imageMagickConvert()
	var $im5fx_blurSteps='1x2,2x2,3x2,4x3,5x3,5x4,6x4,7x5,8x5,9x5';			// Used by v5_blur() to simulate 10 continuous steps of blurring
	var $im5fx_sharpenSteps='1x2,2x2,3x2,2x3,3x3,4x3,3x4,4x4,4x5,5x5';		// Used by v5_sharpen() to simulate 10 continuous steps of sharpening.
	var $pixelLimitGif = 10000;							// This is the limit for the number of pixels in an image before it will be rendered as JPG instead of GIF/PNG
	var $colMap = Array (								// Array mapping HTML color names to RGB values.
		'aqua' => Array(0,255,255),
		'black' => Array(0,0,0),
		'blue' => Array(0,0,255),
		'fuchsia' => Array(255,0,255),
		'gray' => Array(128,128,128),
		'green' => Array(0,128,0),
		'lime' => Array(0,255,0),
		'maroon' => Array(128,0,0),
		'navy' => Array(0,0,128),
		'olive' => Array(128,128,0),
		'purple' => Array(128,0,128),
		'red' => Array(255,0,0),
		'silver' => Array(192,192,192),
		'teal' => Array(0,128,128),
		'yellow' => Array(255,255,0),
		'white' => Array(255,255,255)
	);

		// Charset conversion object:
	var $csConvObj;
	var $nativeCharset='';		// Is set to the native character set of the input strings.





	/**
	 * Init function. Must always call this when using the class.
	 * This function will read the configuration information from $GLOBALS['TYPO3_CONF_VARS']['GFX'] can set some values in internal variables.
	 *
	 * @return	void
	 */
	function init()	{
		$gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX'];

		if (function_exists('imagecreatefromjpeg')&&function_exists('imagejpeg'))	{
			$this->gdlibExtensions .= ',jpg,jpeg';
		}
		if (function_exists('imagecreatefrompng')&&function_exists('imagepng'))	{
			$this->gdlibExtensions .= ',png';
		}
		if (function_exists('imagecreatefromgif')&&function_exists('imagegif'))	{
			$this->gdlibExtensions .= ',gif';
		}
		if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['png_truecolor'])	{
			$this->png_truecolor = true;
		}
		if (!$gfxConf['gdlib_2'] || !function_exists('imagecreatetruecolor'))	{
			$this->truecolor = false;
		}
		if (!$gfxConf['im_version_5'])	{
			$this->im_version_4 = true;
		}

			// When GIFBUILDER gets used in truecolor mode (GD2 required)
		if ($this->truecolor)	{
			if ($this->png_truecolor)	{
				$this->cmds['png'] = '';	// No colors parameter if we generate truecolor images.
			}
			$this->cmds['gif'] = '';	// No colors parameter if we generate truecolor images.
		}

			// Setting default JPG parameters:
		$this->jpegQuality = t3lib_div::intInRange($gfxConf['jpg_quality'], 10, 100, 75);
		$this->cmds['jpg'] = $this->cmds['jpeg'] = '-colorspace RGB -sharpen 50 -quality '.$this->jpegQuality;

		if ($gfxConf['im_combine_filename'])	$this->combineScript=$gfxConf['im_combine_filename'];
		if ($gfxConf['im_noFramePrepended'])	$this->noFramePrepended=1;

		if ($gfxConf['gdlib_2'])	{
			$this->GD2 = 1;
			$this->imagecopyresized_fix = $gfxConf['gdlib_2']==='no_imagecopyresized_fix' ? 0 : 1;
		}
		if ($gfxConf['gdlib_png'])	{
			$this->gifExtension='png';
		}
		if ($gfxConf['TTFLocaleConv']) {
			$this->TTFLocaleConv = $gfxConf['TTFLocaleConv'];
		}
		if ($gfxConf['enable_typo3temp_db_tracking']) {
			$this->enable_typo3temp_db_tracking = $gfxConf['enable_typo3temp_db_tracking'];
		}

		$this->imageFileExt = $gfxConf['imagefile_ext'];

			// This should be set if ImageMagick ver. 5+ is used.
		if ($gfxConf['im_negate_mask'])	{
				// Boolean. Indicates if the mask images should be inverted first.
				// This depends of the ImageMagick version. Below ver. 5.1 this should be false.
				// Above ImageMagick version 5.2+ it should be true.
				// Just set the flag if the masks works opposite the intension!
			$this->maskNegate = ' -negate';
		}
		if ($gfxConf['im_no_effects'])	{
				// Boolean. This is necessary if using ImageMagick 5+.
				// Approved version for using effects is version 4.2.9.
				// Effects in Imagemagick 5+ tends to render very slowly!!
				// - therefore must be disabled in order not to perform sharpen, blurring and such.
			$this->NO_IM_EFFECTS = 1;

			$this->cmds['jpg'] = $this->cmds['jpeg'] = '-colorspace RGB -quality '.$this->jpegQuality;
		}
			// ... but if 'im_v5effects' is set, don't care about 'im_no_effects'
		if ($gfxConf['im_v5effects'])	{
			$this->NO_IM_EFFECTS = 0;
			$this->V5_EFFECTS = 1;

			if ($gfxConf['im_v5effects']>0)	{
				$this->cmds['jpg'] = $this->cmds['jpeg'] = '-colorspace RGB -quality '.intval($gfxConf['jpg_quality']).$this->v5_sharpen(10);
			}
		}

		if (!$gfxConf['im'])	{
			$this->NO_IMAGE_MAGICK = 1;
		}
			// Secures that images are not scaled up.
		if ($gfxConf['im_noScaleUp']) {
			$this->mayScaleUp=0;
		}

		if (TYPO3_MODE=='FE')	{
			$this->csConvObj = &$GLOBALS['TSFE']->csConvObj;
		} elseif(is_object($GLOBALS['LANG']))	{	// BE assumed:
			$this->csConvObj = &$GLOBALS['LANG']->csConvObj;
		} else	{	// The object may not exist yet, so we need to create it now. Happens in the Install Tool for example.
			$this->csConvObj = t3lib_div::makeInstance('t3lib_cs');
		}
		$this->nativeCharset = $GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'];
	}
















	/*************************************************
	 *
	 * Layering images / "IMAGE" GIFBUILDER object
	 *
	 *************************************************/

	/**
	 * Implements the "IMAGE" GIFBUILDER object, when the "mask" property is true.
	 * It reads the two images defined by $conf['file'] and $conf['mask'] and copies the $conf['file'] onto the input image pointer image using the $conf['mask'] as a grayscale mask
	 * The operation involves ImageMagick for combining.
	 *
	 * @param	pointer		GDlib image pointer
	 * @param	array		TypoScript array with configuration for the GIFBUILDER object.
	 * @param	array		The current working area coordinates.
	 * @return	void
	 * @see tslib_gifBuilder::make()
	 */
	function maskImageOntoImage(&$im,$conf,$workArea)	{
		if ($conf['file'] && $conf['mask'])	{
			$imgInf = pathinfo($conf['file']);
			$imgExt = strtolower($imgInf['extension']);
			if (!t3lib_div::inList($this->gdlibExtensions, $imgExt))	{
				$BBimage = $this->imageMagickConvert($conf['file'],$this->gifExtension,'','','','','');
			} else	{
				$BBimage = $this->getImageDimensions($conf['file']);
			}
			$maskInf = pathinfo($conf['mask']);
			$maskExt = strtolower($maskInf['extension']);
			if (!t3lib_div::inList($this->gdlibExtensions, $maskExt))	{
				$BBmask = $this->imageMagickConvert($conf['mask'],$this->gifExtension,'','','','','');
			} else	{
				$BBmask = $this->getImageDimensions($conf['mask']);
			}
			if ($BBimage && $BBmask)	{
				$w = imagesx($im);
				$h = imagesy($im);
				$tmpStr = $this->randomName();
				$theImage = $tmpStr.'_img.'.$this->gifExtension;
				$theDest = $tmpStr.'_dest.'.$this->gifExtension;
				$theMask = $tmpStr.'_mask.'.$this->gifExtension;
						// prepare overlay image
				$cpImg = $this->imageCreateFromFile($BBimage[3]);
				$destImg = $this->imagecreate($w,$h);
				$Bcolor = ImageColorAllocate($destImg, 0,0,0);
				ImageFilledRectangle($destImg, 0, 0, $w, $h, $Bcolor);
				$this->copyGifOntoGif($destImg,$cpImg,$conf,$workArea);
				$this->ImageWrite($destImg, $theImage);
				imageDestroy($cpImg);
				imageDestroy($destImg);
						// prepare mask image
				$cpImg = $this->imageCreateFromFile($BBmask[3]);
				$destImg = $this->imagecreate($w,$h);
				$Bcolor = ImageColorAllocate($destImg, 0, 0, 0);
				ImageFilledRectangle($destImg, 0, 0, $w, $h, $Bcolor);
				$this->copyGifOntoGif($destImg,$cpImg,$conf,$workArea);
				$this->ImageWrite($destImg, $theMask);
				imageDestroy($cpImg);
				imageDestroy($destImg);
					// mask the images
				$this->ImageWrite($im, $theDest);

				$this->combineExec($theDest,$theImage,$theMask,$theDest, true);		// Let combineExec handle maskNegation

				$backIm = $this->imageCreateFromFile($theDest);	// The main image is loaded again...
				if ($backIm)	{	// ... and if nothing went wrong we load it onto the old one.
					ImageColorTransparent($backIm,-1);
					$im = $backIm;
				}
					// unlink files from process
				if (!$this->dontUnlinkTempFiles)	{
					unlink($theDest);
					unlink($theImage);
					unlink($theMask);
				}
			}
		}
	}

	/**
	 * Implements the "IMAGE" GIFBUILDER object, when the "mask" property is false (using only $conf['file'])
	 *
	 * @param	pointer		GDlib image pointer
	 * @param	array		TypoScript array with configuration for the GIFBUILDER object.
	 * @param	array		The current working area coordinates.
	 * @return	void
	 * @see tslib_gifBuilder::make(), maskImageOntoImage()
	 */
	function copyImageOntoImage(&$im,$conf,$workArea)	{
		if ($conf['file'])	{
			if (!t3lib_div::inList($this->gdlibExtensions, $conf['BBOX'][2]))	{
				$conf['BBOX']=$this->imageMagickConvert($conf['BBOX'][3],$this->gifExtension,'','','','','');
				$conf['file']=$conf['BBOX'][3];
			}
			$cpImg = $this->imageCreateFromFile($conf['file']);
			$this->copyGifOntoGif($im,$cpImg,$conf,$workArea);
			imageDestroy($cpImg);
		}
	}

	/**
	 * Copies two GDlib image pointers onto each other, using TypoScript configuration from $conf and the input $workArea definition.
	 *
	 * @param	pointer		GDlib image pointer, destination (bottom image)
	 * @param	pointer		GDlib image pointer, source (top image)
	 * @param	array		TypoScript array with the properties for the IMAGE GIFBUILDER object. Only used for the "tile" property value.
	 * @param	array		Work area
	 * @return	void		Works on the $im image pointer
	 * @access private
	 */
	function copyGifOntoGif(&$im,$cpImg,$conf,$workArea)	{
		$cpW = imagesx($cpImg);
		$cpH = imagesy($cpImg);
		$tile = t3lib_div::intExplode(',',$conf['tile']);
		$tile[0] = t3lib_div::intInRange($tile[0],1,20);
		$tile[1] = t3lib_div::intInRange($tile[1],1,20);
		$cpOff = $this->objPosition($conf,$workArea,Array($cpW*$tile[0],$cpH*$tile[1]));

		for ($xt=0;$xt<$tile[0];$xt++)	{
			$Xstart=$cpOff[0]+$cpW*$xt;
			if ($Xstart+$cpW > $workArea[0])	{	// if this image is inside of the workArea, then go on
					// X:
				if ($Xstart < $workArea[0])	{
					$cpImgCutX = $workArea[0]-$Xstart;
					$Xstart = $workArea[0];
				} else {
					$cpImgCutX = 0;
				}
				$w = $cpW-$cpImgCutX;
				if ($Xstart > $workArea[0]+$workArea[2]-$w)	{
					$w = $workArea[0]+$workArea[2]-$Xstart;
				}
				if ($Xstart < $workArea[0]+$workArea[2])	{	// if this image is inside of the workArea, then go on
						// Y:
					for ($yt=0;$yt<$tile[1];$yt++)	{
						$Ystart=$cpOff[1]+$cpH*$yt;
						if ($Ystart+$cpH > $workArea[1])	{	// if this image is inside of the workArea, then go on
							if ($Ystart < $workArea[1])	{
								$cpImgCutY = $workArea[1]-$Ystart;
								$Ystart = $workArea[1];
							} else {
								$cpImgCutY = 0;
							}
							$h = $cpH-$cpImgCutY;
							if ($Ystart > $workArea[1]+$workArea[3]-$h)	{
								$h = $workArea[1]+$workArea[3]-$Ystart;
							}
							if ($Ystart < $workArea[1]+$workArea[3])	{	// if this image is inside of the workArea, then go on
								$this->imagecopyresized($im, $cpImg, $Xstart, $Ystart, $cpImgCutX, $cpImgCutY, $w, $h, $w, $h);
							}
						}
					}  // Y:
				}
			}
		}
	}

	/**
	 * Alternative function for using the similar PHP function imagecopyresized(). Used for GD2 only.
	 *
	 * OK, the reason for this stupid fix is the following story:
	 * GD1.x was capable of copying two images together and combining their palettes! GD2 is apparently not.
	 * With GD2 only the palette of the dest-image is used which mostly results in totally black images when trying to
	 * copy a color-ful image onto the destination.
	 * The GD2-fix is to
	 * 		1) Create a blank TRUE-COLOR image
	 * 		2) Copy the destination image onto that one
	 * 		3) Then do the actual operation; Copying the source (top image) onto that
	 * 		4) ... and return the result pointer.
	 * 		5) Reduce colors (if we do not, the result may become strange!)
	 * It works, but the resulting images is now a true-color PNG which may be very large.
	 * So, why not use 'imagetruecolortopalette ($im, TRUE, 256)' - well because it does NOT WORK! So simple is that.
	 *
	 * For parameters, see PHP function "imagecopyresized()"
	 *
	 * @param	pointer		see PHP function "imagecopyresized()"
	 * @param	pointer		see PHP function "imagecopyresized()"
	 * @param	integer		see PHP function "imagecopyresized()"
	 * @param	integer		see PHP function "imagecopyresized()"
	 * @param	integer		see PHP function "imagecopyresized()"
	 * @param	integer		see PHP function "imagecopyresized()"
	 * @param	integer		see PHP function "imagecopyresized()"
	 * @param	integer		see PHP function "imagecopyresized()"
	 * @param	integer		see PHP function "imagecopyresized()"
	 * @param	integer		see PHP function "imagecopyresized()"
	 * @return	void
	 * @access private
	 * @see t3lib_iconWorks::imagecopyresized()
	 */
	function imagecopyresized(&$im, $cpImg, $Xstart, $Ystart, $cpImgCutX, $cpImgCutY, $w, $h, $w, $h)	{
		if ($this->imagecopyresized_fix)	{
			$im_base = $this->imagecreate(imagesx($im), imagesy($im));	// Make true color image
			imagecopyresized($im_base, $im, 0,0,0,0, imagesx($im),imagesy($im),imagesx($im),imagesy($im));	// Copy the source image onto that
			imagecopyresized($im_base, $cpImg, $Xstart, $Ystart, $cpImgCutX, $cpImgCutY, $w, $h, $w, $h);	// Then copy the $cpImg onto that (the actual operation!)
			$im = $im_base;	// Set pointer
			if (!$this->truecolor)	{
				$this->makeEffect($im, Array('value'=>'colors='.t3lib_div::intInRange($this->setup['reduceColors'], 256, $this->truecolorColors, 256)));		// Reduce to "reduceColors" colors - make SURE that IM is working then!
			}
		} else {
			imagecopyresized($im, $cpImg, $Xstart, $Ystart, $cpImgCutX, $cpImgCutY, $w, $h, $w, $h);
		}
	}






















	/********************************
	 *
	 * Text / "TEXT" GIFBUILDER object
	 *
	 ********************************/

	/**
	 * Implements the "TEXT" GIFBUILDER object
	 *
	 * @param	pointer		GDlib image pointer
	 * @param	array		TypoScript array with configuration for the GIFBUILDER object.
	 * @param	array		The current working area coordinates.
	 * @return	void
	 * @see tslib_gifBuilder::make()
	 */
	function makeText(&$im,$conf,$workArea)	{
			// Spacing
		list($spacing,$wordSpacing) = $this->calcWordSpacing($conf);
			// Position
		$txtPos = $this->txtPosition($conf,$workArea,$conf['BBOX']);
		$theText = $this->recodeString($conf['text']);

		if ($conf['imgMap'] && is_array($conf['imgMap.']))	{
			$this->addToMap($this->calcTextCordsForMap($conf['BBOX'][2],$txtPos, $conf['imgMap.']), $conf['imgMap.']);
		}
		if (!$conf['hideButCreateMap'])	{
				// Font Color:
			$cols=$this->convertColor($conf['fontColor']);
				// NiceText is calculated
			if (!$conf['niceText']) {
					// Font Color is reserved:
				if (!$this->truecolor)	{
					$reduce = t3lib_div::intInRange($this->setup['reduceColors'], 256, $this->truecolorColors, 256);
					$this->reduceColors($im, $reduce-49, $reduce-50);	// If "reduce-49" colors (or more) are used reduce them to "reduce-50"
				}
				$Fcolor = ImageColorAllocate($im, $cols[0],$cols[1],$cols[2]);
					// antiAliasing is setup:
				$Fcolor = ($conf['antiAlias']) ? $Fcolor : -$Fcolor;

				for ($a=0; $a<$conf['iterations']; $a++)	{
					if ($spacing || $wordSpacing)	{		// If any kind of spacing applys, we use this function:
						$this->SpacedImageTTFText($im, $conf['fontSize'], $conf['angle'], $txtPos[0], $txtPos[1], $Fcolor, t3lib_stdGraphic::prependAbsolutePath($conf['fontFile']), $theText, $spacing, $wordSpacing, $conf['splitRendering.']);
					} else {
						$this->ImageTTFTextWrapper($im, $conf['fontSize'], $conf['angle'], $txtPos[0], $txtPos[1], $Fcolor, $conf['fontFile'], $theText, $conf['splitRendering.']);
					}
				}
			} else {		// NICETEXT::
					// options anti_aliased and iterations is NOT available when doing this!!
				$w = imagesx($im);
				$h = imagesy($im);
				$tmpStr = $this->randomName();

				$fileMenu = $tmpStr.'_menuNT.'.$this->gifExtension;
				$fileColor = $tmpStr.'_colorNT.'.$this->gifExtension;
				$fileMask = $tmpStr.'_maskNT.'.$this->gifExtension;
					// Scalefactor
				$sF = t3lib_div::intInRange($conf['niceText.']['scaleFactor'],2,5);
				$newW = ceil($sF*imagesx($im));
				$newH = ceil($sF*imagesy($im));

					// Make mask
				$maskImg = $this->imagecreate($newW, $newH);
				$Bcolor = ImageColorAllocate($maskImg, 255,255,255);
				ImageFilledRectangle($maskImg, 0, 0, $newW, $newH, $Bcolor);
				$Fcolor = ImageColorAllocate($maskImg, 0,0,0);
				if ($spacing || $wordSpacing)	{		// If any kind of spacing applys, we use this function:
					$this->SpacedImageTTFText($maskImg, $conf['fontSize'], $conf['angle'], $txtPos[0], $txtPos[1], $Fcolor, t3lib_stdGraphic::prependAbsolutePath($conf['fontFile']), $theText, $spacing, $wordSpacing, $conf['splitRendering.'],$sF);
				} else {
					$this->ImageTTFTextWrapper($maskImg, $conf['fontSize'], $conf['angle'], $txtPos[0], $txtPos[1], $Fcolor, $conf['fontFile'], $theText, $conf['splitRendering.'],$sF);
				}
				$this->ImageWrite($maskImg, $fileMask);
				ImageDestroy($maskImg);

					// Downscales the mask
				if ($this->NO_IM_EFFECTS)	{
					if ($this->maskNegate)	{
						$command = trim($this->scalecmd.' '.$w.'x'.$h.'!');		// Negate 2 times makes no negate...
					} else {
						$command = trim($this->scalecmd.' '.$w.'x'.$h.'! -negate');
					}
				} else {
					if ($this->maskNegate)	{
						$command = trim($conf['niceText.']['before'].' '.$this->scalecmd.' '.$w.'x'.$h.'! '.$conf['niceText.']['after']);
					} else {
						$command = trim($conf['niceText.']['before'].' '.$this->scalecmd.' '.$w.'x'.$h.'! '.$conf['niceText.']['after'].' -negate');
					}
					if ($conf['niceText.']['sharpen']) {
						if ($this->V5_EFFECTS)	{
							$command.=$this->v5_sharpen($conf['niceText.']['sharpen']);
						} else {
							$command.=' -sharpen '.t3lib_div::intInRange($conf['niceText.']['sharpen'],1,99);
						}
					}
				}

				$this->imageMagickExec($fileMask,$fileMask,$command);

					// Make the color-file
				$colorImg = $this->imagecreate($w,$h);
				$Ccolor = ImageColorAllocate($colorImg, $cols[0],$cols[1],$cols[2]);
				ImageFilledRectangle($colorImg, 0, 0, $w, $h, $Ccolor);
				$this->ImageWrite($colorImg, $fileColor);
				ImageDestroy($colorImg);

					// The mask is applied
				$this->ImageWrite($im, $fileMenu);	// The main pictures is saved temporarily

				$this->combineExec($fileMenu,$fileColor,$fileMask, $fileMenu);

				$backIm = $this->imageCreateFromFile($fileMenu);	// The main image is loaded again...
				if ($backIm)	{	// ... and if nothing went wrong we load it onto the old one.
					ImageColorTransparent($backIm,-1);
					$im = $backIm;
				}

					// Deleting temporary files;
				if (!$this->dontUnlinkTempFiles)	{
					unlink($fileMenu);
					unlink($fileColor);
					unlink($fileMask);
				}
			}
		}
	}

	/**
	 * Calculates text position for printing the text onto the image based on configuration like alignment and workarea.
	 *
	 * @param	array		TypoScript array for the TEXT GIFBUILDER object
	 * @param	array		Workarea definition
	 * @param	array		Bounding box information, was set in tslib_gifBuilder::start()
	 * @return	array		[0]=x, [1]=y, [2]=w, [3]=h
	 * @access private
	 * @see makeText()
	 */
	function txtPosition($conf,$workArea,$BB) {
		$bbox = $BB[2];
		$angle=intval($conf['angle'])/180*pi();
		$conf['angle']=0;
		$straightBB = $this->calcBBox($conf);

			// offset, align, valign, workarea
		$result=Array();	// [0]=x, [1]=y, [2]=w, [3]=h
		$result[2] = $BB[0];
		$result[3] = $BB[1];
		$w=$workArea[2];
		$h=$workArea[3];

		switch($conf['align'])	{
			case 'right':
			case 'center':
				$factor=abs(cos($angle));
				$sign=(cos($angle)<0)?-1:1;
				$len1 = $sign*$factor*$straightBB[0];
				$len2= $sign*$BB[0];
				$result[0] = $w-ceil($len2*$factor+(1-$factor)*$len1);

				$factor=abs(sin($angle));
				$sign=(sin($angle)<0)?-1:1;
				$len1= $sign*$factor*$straightBB[0];
				$len2= $sign*$BB[1];
				$result[1]=ceil($len2*$factor+(1-$factor)*$len1);
			break;
		}
		switch($conf['align'])	{
			case 'right':
			break;
			case 'center':
				$result[0] = round(($result[0])/2);
				$result[1] = round(($result[1])/2);
			break;
			default:
				$result[0]=0;
				$result[1]=0;
			break;
		}
		$result = $this->applyOffset($result,t3lib_div::intExplode(',',$conf['offset']));
		$result = $this->applyOffset($result,$workArea);
		return $result;
	}

	/**
	 * Calculates bounding box information for the TEXT GIFBUILDER object.
	 *
	 * @param	array		TypoScript array for the TEXT GIFBUILDER object
	 * @return	array		Array with three keys [0]/[1] being x/y and [2] being the bounding box array
	 * @access private
	 * @see txtPosition(), tslib_gifBuilder::start()
	 */
	function calcBBox($conf)	{
		$sF = $this->getTextScalFactor($conf);
		list($spacing,$wordSpacing) = $this->calcWordSpacing($conf, $sF);
		$theText = $this->recodeString($conf['text']);

		$charInf = $this->ImageTTFBBoxWrapper($conf['fontSize'], $conf['angle'], $conf['fontFile'], $theText, $conf['splitRendering.'],$sF);
		$theBBoxInfo = $charInf;
		if ($conf['angle'])	{
			$xArr = Array($charInf[0],$charInf[2],$charInf[4],$charInf[6]);
			$yArr = Array($charInf[1],$charInf[3],$charInf[5],$charInf[7]);
			$x=max($xArr)-min($xArr);
			$y=max($yArr)-min($yArr);
		} else {
			$x = ($charInf[2]-$charInf[0]);
			$y = ($charInf[1]-$charInf[7]);
		}
		if ($spacing || $wordSpacing)	{		// If any kind of spacing applys, we use this function:
			$x=0;
			if (!$spacing && $wordSpacing)	{
				$bits = explode(' ',$theText);
				while(list(,$word)=each($bits))	{
					$word.=' ';
					$wordInf = $this->ImageTTFBBoxWrapper($conf['fontSize'], $conf['angle'], $conf['fontFile'], $word, $conf['splitRendering.'],$sF);
					$wordW = ($wordInf[2]-$wordInf[0]);
					$x+=$wordW+$wordSpacing;
				}
			} else {
				$utf8Chars = $this->singleChars($theText);
					// For each UTF-8 char, do:
				foreach($utf8Chars as $char)	{
					$charInf = $this->ImageTTFBBoxWrapper($conf['fontSize'], $conf['angle'], $conf['fontFile'], $char, $conf['splitRendering.'],$sF);
					$charW = ($charInf[2]-$charInf[0]);
					$x+=$charW+(($char==' ')?$wordSpacing:$spacing);
				}
			}
		}

		if ($sF>1) {
			$x = ceil($x/$sF);
			$y = ceil($y/$sF);
			if (is_array($theBBoxInfo))	{
				reset($theBBoxInfo);
				while(list($key,$val)=each($theBBoxInfo))	{
					$theBBoxInfo[$key]=ceil($theBBoxInfo[$key]/$sF);
				}
			}
		}
		return array($x,$y,$theBBoxInfo);
	}

	/**
	 * Adds an <area> tag to the internal variable $this->map which is used to accumulate the content for an ImageMap
	 *
	 * @param	array		Coordinates for a polygon image map as created by ->calcTextCordsForMap()
	 * @param	array		Configuration for "imgMap." property of a TEXT GIFBUILDER object.
	 * @return	void
	 * @access private
	 * @see makeText(), calcTextCordsForMap()
	 */
	function addToMap($cords,$conf)	{
		$JS = $conf['noBlur'] ? '' : ' onfocus="blurLink(this);"';

		$this->map.='<area'.
				' shape="poly"'.
				' coords="'.implode(',',$cords).'"'.
				' href="'.htmlspecialchars($conf['url']).'"'.
				($conf['target'] ? ' target="'.htmlspecialchars($conf['target']).'"' : '').
				$JS.
				(strlen($conf['titleText']) ? ' title="'.htmlspecialchars($conf['titleText']).'"' : '').
				' alt="'.htmlspecialchars($conf['altText']).'" />';
	}

	/**
	 * Calculating the coordinates for a TEXT string on an image map. Used in an <area> tag
	 *
	 * @param	array		Coordinates (from BBOX array)
	 * @param	array		Offset array
	 * @param	array		Configuration for "imgMap." property of a TEXT GIFBUILDER object.
	 * @return	array
	 * @access private
	 * @see makeText(), calcTextCordsForMap()
	 */
	function calcTextCordsForMap($cords,$offset, $conf)	{
		$pars = t3lib_div::intExplode(',',$conf['explode'].',');

		$newCords[0] = $cords[0]+$offset[0]-$pars[0];
		$newCords[1] = $cords[1]+$offset[1]+$pars[1];
		$newCords[2] = $cords[2]+$offset[0]+$pars[0];
		$newCords[3] = $cords[3]+$offset[1]+$pars[1];
		$newCords[4] = $cords[4]+$offset[0]+$pars[0];
		$newCords[5] = $cords[5]+$offset[1]-$pars[1];
		$newCords[6] = $cords[6]+$offset[0]-$pars[0];
		$newCords[7] = $cords[7]+$offset[1]-$pars[1];

		return $newCords;
	}

	/**
	 * Printing text onto an image like the PHP function imageTTFText does but in addition it offers options for spacing of letters and words.
	 * Spacing is done by printing one char at a time and this means that the spacing is rather uneven and probably not very nice.
	 * See
	 *
	 * @param	pointer		(See argument for PHP function imageTTFtext())
	 * @param	integer		(See argument for PHP function imageTTFtext())
	 * @param	integer		(See argument for PHP function imageTTFtext())
	 * @param	integer		(See argument for PHP function imageTTFtext())
	 * @param	integer		(See argument for PHP function imageTTFtext())
	 * @param	integer		(See argument for PHP function imageTTFtext())
	 * @param	string		(See argument for PHP function imageTTFtext())
	 * @param	string		(See argument for PHP function imageTTFtext()). UTF-8 string, possibly with entities in.
	 * @param	integer		The spacing of letters in pixels
	 * @param	integer		The spacing of words in pixels
	 * @param	array		$splitRenderingConf array
	 * @param	integer		Scale factor
	 * @return	void
	 * @access private
	 */
	function SpacedImageTTFText(&$im, $fontSize, $angle, $x, $y, $Fcolor, $fontFile, $text, $spacing, $wordSpacing, $splitRenderingConf, $sF=1)	{

		$spacing*=$sF;
		$wordSpacing*=$sF;

		if (!$spacing && $wordSpacing)	{
			$bits = explode(' ',$text);
			reset($bits);
			while(list(,$word)=each($bits))	{
				$word.=' ';
				$word = $word;
				$wordInf = $this->ImageTTFBBoxWrapper($fontSize, $angle, $fontFile, $word, $splitRenderingConf ,$sF);
				$wordW = ($wordInf[2]-$wordInf[0]);
				$this->ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $Fcolor, $fontFile, $word, $splitRenderingConf, $sF);
				$x+=$wordW+$wordSpacing;
			}
		} else {
			$utf8Chars = $this->singleChars($text);
				// For each UTF-8 char, do:
			foreach($utf8Chars as $char)	{
				$charInf = $this->ImageTTFBBoxWrapper($fontSize, $angle, $fontFile, $char, $splitRenderingConf, $sF);
				$charW = ($charInf[2]-$charInf[0]);
				$this->ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $Fcolor, $fontFile, $char, $splitRenderingConf, $sF);
				$x+=$charW+(($char==' ')?$wordSpacing:$spacing);
			}
		}
	}

	/**
	 * Function that finds the right fontsize that will render the textstring within a certain width
	 *
	 * @param	array		The TypoScript properties of the TEXT GIFBUILDER object
	 * @return	integer		The new fontSize
	 * @access private
	 * @author Rene Fritz <r.fritz@colorcube.de>
	 * @see tslib_gifBuilder::start()
	 */
	function fontResize($conf) {
		// you have to use +calc options like [10.h] in 'offset' to get the right position of your text-image, if you use +calc in XY height!!!!
		$maxWidth = intval($conf['maxWidth']);
		list($spacing,$wordSpacing) = $this->calcWordSpacing($conf);
		if ($maxWidth)	{
			if ($spacing || $wordSpacing)	{		// If any kind of spacing applys, we use this function:
				return $conf['fontSize'];
				//  ################ no calc for spacing yet !!!!!!
			} else {
				do {
						// determine bounding box.
					$bounds = $this->ImageTTFBBoxWrapper($conf['fontSize'], $conf['angle'], $conf['fontFile'], $this->recodeString($conf['text']), $conf['splitRendering.']);
					if ($conf['angle']< 0) {
						$pixelWidth = abs($bounds[4]-$bounds[0]);
					} elseif ($conf['angle'] > 0) {
						$pixelWidth = abs($bounds[2]-$bounds[6]);
					} else {
						$pixelWidth = abs($bounds[4]-$bounds[6]);
					}

						// Size is fine, exit:
					if ($pixelWidth <= $maxWidth)	{
						break;
					} else {
						$conf['fontSize']--;
					}
				} while ($conf['fontSize']>1);
			}//if spacing
		}
		return $conf['fontSize'];
	}

	/**
	 * Wrapper for ImageTTFBBox
	 *
	 * @param	integer		(See argument for PHP function ImageTTFBBox())
	 * @param	integer		(See argument for PHP function ImageTTFBBox())
	 * @param	string		(See argument for PHP function ImageTTFBBox())
	 * @param	string		(See argument for PHP function ImageTTFBBox())
	 * @param	array		Split-rendering configuration
	 * @param	integer		Scale factor
	 * @return	array		Information array.
	 */
	function ImageTTFBBoxWrapper($fontSize, $angle, $fontFile, $string, $splitRendering, $sF=1)	{

			// Initialize:
		$offsetInfo = array();
		$stringParts = $this->splitString($string,$splitRendering,$fontSize,$fontFile);

			// Traverse string parts:
		foreach($stringParts as $strCfg)	{
			$fontFile = t3lib_stdGraphic::prependAbsolutePath($strCfg['fontFile']);
			if (is_readable($fontFile)) {

					// Calculate Bounding Box for part:
				$calc = ImageTTFBBox(t3lib_div::freetypeDpiComp($sF*$strCfg['fontSize']), $angle, $fontFile, $strCfg['str']);

					// Calculate offsets:
				if (!count($offsetInfo))	{
					$offsetInfo = $calc;	// First run, just copy over.
				} else {
					$offsetInfo[2]+=$calc[2]-$calc[0]+intval($splitRendering['compX'])+intval($strCfg['xSpaceBefore'])+intval($strCfg['xSpaceAfter']);
					$offsetInfo[3]+=$calc[3]-$calc[1]-intval($splitRendering['compY'])-intval($strCfg['ySpaceBefore'])-intval($strCfg['ySpaceAfter']);
					$offsetInfo[4]+=$calc[4]-$calc[6]+intval($splitRendering['compX'])+intval($strCfg['xSpaceBefore'])+intval($strCfg['xSpaceAfter']);
					$offsetInfo[5]+=$calc[5]-$calc[7]-intval($splitRendering['compY'])-intval($strCfg['ySpaceBefore'])-intval($strCfg['ySpaceAfter']);
				}

			} else {
				debug('cannot read file: '.$fontFile, 't3lib_stdGraphic::ImageTTFBBoxWrapper()');
			}
		}

		return $offsetInfo;
	}

	/**
	 * Wrapper for ImageTTFText
	 *
	 * @param	pointer		(See argument for PHP function imageTTFtext())
	 * @param	integer		(See argument for PHP function imageTTFtext())
	 * @param	integer		(See argument for PHP function imageTTFtext())
	 * @param	integer		(See argument for PHP function imageTTFtext())
	 * @param	integer		(See argument for PHP function imageTTFtext())
	 * @param	integer		(See argument for PHP function imageTTFtext())
	 * @param	string		(See argument for PHP function imageTTFtext())
	 * @param	string		(See argument for PHP function imageTTFtext()). UTF-8 string, possibly with entities in.
	 * @param	array		Split-rendering configuration
	 * @param	integer		Scale factor
	 * @return	void
	 */
	function ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $color, $fontFile, $string, $splitRendering,$sF=1)	{

			// Initialize:
		$stringParts = $this->splitString($string,$splitRendering,$fontSize,$fontFile);
		$x = ceil($sF*$x);
		$y = ceil($sF*$y);

			// Traverse string parts:
		foreach($stringParts as $i => $strCfg)	{

				// Initialize:
			$colorIndex = $color;

				// Set custom color if any (only when niceText is off):
			if ($strCfg['color'] && $sF==1)	{
				$cols = $this->convertColor($strCfg['color']);
				$colorIndex = ImageColorAllocate($im, $cols[0],$cols[1],$cols[2]);
				$colorIndex = $color >= 0 ? $colorIndex : -$colorIndex;
			}

				// Setting xSpaceBefore
			if ($i)	{
				$x+= intval($strCfg['xSpaceBefore']);
				$y-= intval($strCfg['ySpaceBefore']);
			}

			$fontFile = t3lib_stdGraphic::prependAbsolutePath($strCfg['fontFile']);
			if (is_readable($fontFile)) {

					// Render part:
				ImageTTFText($im, t3lib_div::freetypeDpiComp($sF*$strCfg['fontSize']), $angle, $x, $y, $colorIndex, $fontFile, $strCfg['str']);

					// Calculate offset to apply:
				$wordInf = ImageTTFBBox(t3lib_div::freetypeDpiComp($sF*$strCfg['fontSize']), $angle, t3lib_stdGraphic::prependAbsolutePath($strCfg['fontFile']), $strCfg['str']);
				$x+= $wordInf[2]-$wordInf[0]+intval($splitRendering['compX'])+intval($strCfg['xSpaceAfter']);
				$y+= $wordInf[5]-$wordInf[7]-intval($splitRendering['compY'])-intval($strCfg['ySpaceAfter']);

			} else {
				debug('cannot read file: '.$fontFile, 't3lib_stdGraphic::ImageTTFTextWrapper()');
			}

		}
	}

	/**
	 * Splitting a string for ImageTTFBBox up into an array where each part has its own configuration options.
	 *
	 * @param	string		UTF-8 string
	 * @param	array		Split-rendering configuration from GIFBUILDER TEXT object.
	 * @param	integer		Current fontsize
	 * @param	string		Current font file
	 * @return	array		Array with input string splitted according to configuration
	 */
	function splitString($string,$splitRendering,$fontSize,$fontFile)	{

			// Initialize by setting the whole string and default configuration as the first entry.
		$result = array();
		$result[] = array(
			'str' => $string,
			'fontSize' => $fontSize,
			'fontFile' => $fontFile
		);

			// Traverse the split-rendering configuration:
			// Splitting will create more entries in $result with individual configurations.
		if (is_array($splitRendering))	{
			$sKeyArray = t3lib_TStemplate::sortedKeyList($splitRendering);

				// Traverse configured options:
			foreach($sKeyArray as $key)	{
				$cfg = $splitRendering[$key.'.'];

					// Process each type of split rendering keyword:
				switch((string)$splitRendering[$key])	{
					case 'highlightWord':
						if (strlen($cfg['value']))	{
							$newResult = array();

								// Traverse the current parts of the result array:
							foreach($result as $part)	{
									// Explode the string value by the word value to highlight:
								$explodedParts = explode($cfg['value'],$part['str']);
								foreach($explodedParts as $c => $expValue)	{
									if (strlen($expValue))	{
										$newResult[] = array_merge($part,array('str' => $expValue));
									}
									if ($c+1 < count($explodedParts))	{
										$newResult[] = array(
											'str' => $cfg['value'],
											'fontSize' => $cfg['fontSize'] ? $cfg['fontSize'] : $part['fontSize'],
											'fontFile' => $cfg['fontFile'] ? $cfg['fontFile'] : $part['fontFile'],
											'color' => $cfg['color'],
											'xSpaceBefore' => $cfg['xSpaceBefore'],
											'xSpaceAfter' => $cfg['xSpaceAfter'],
											'ySpaceBefore' => $cfg['ySpaceBefore'],
											'ySpaceAfter' => $cfg['ySpaceAfter'],
										);
									}
								}
							}

								// Set the new result as result array:
							if (count($newResult))	{
								$result = $newResult;
							}
						}
					break;
					case 'charRange':
						if (strlen($cfg['value']))	{

								// Initialize range:
							$ranges = t3lib_div::trimExplode(',',$cfg['value'],1);
							foreach($ranges as $i => $rangeDef)	{
								$ranges[$i] = t3lib_div::intExplode('-',$ranges[$i]);
								if (!isset($ranges[$i][1]))	$ranges[$i][1] = $ranges[$i][0];
							}
							$newResult = array();

								// Traverse the current parts of the result array:
							foreach($result as $part)	{

									// Initialize:
								$currentState = -1;
								$bankAccum = '';

									// Explode the string value by the word value to highlight:
								$utf8Chars = $this->singleChars($part['str']);
								foreach($utf8Chars as $utfChar)	{

										// Find number and evaluate position:
									$uNumber = $this->csConvObj->utf8CharToUnumber($utfChar);
									$inRange = 0;
									foreach($ranges as $rangeDef)	{
										if ($uNumber >= $rangeDef[0] && (!$rangeDef[1] || $uNumber <= $rangeDef[1])) {
											$inRange = 1;
											break;
										}
									}
									if ($currentState==-1)	$currentState = $inRange;	// Initialize first char

										// Switch bank:
									if ($inRange != $currentState && !t3lib_div::inList('32,10,13,9',$uNumber))	{

											// Set result:
										if (strlen($bankAccum))	{
											$newResult[] = array(
												'str' => $bankAccum,
												'fontSize' => $currentState && $cfg['fontSize'] ? $cfg['fontSize'] : $part['fontSize'],
												'fontFile' => $currentState && $cfg['fontFile'] ? $cfg['fontFile'] : $part['fontFile'],
												'color' => $currentState ? $cfg['color'] : '',
												'xSpaceBefore' => $currentState ? $cfg['xSpaceBefore'] : '',
												'xSpaceAfter' => $currentState ? $cfg['xSpaceAfter'] : '',
												'ySpaceBefore' => $currentState ? $cfg['ySpaceBefore'] : '',
												'ySpaceAfter' => $currentState ? $cfg['ySpaceAfter'] : '',
											);
										}

											// Initialize new settings:
										$currentState = $inRange;
										$bankAccum = '';
									}

										// Add char to bank:
									$bankAccum.=$utfChar;
								}

									// Set result for FINAL part:
								if (strlen($bankAccum))	{
									$newResult[] = array(
										'str' => $bankAccum,
										'fontSize' => $currentState && $cfg['fontSize'] ? $cfg['fontSize'] : $part['fontSize'],
										'fontFile' => $currentState && $cfg['fontFile'] ? $cfg['fontFile'] : $part['fontFile'],
										'color' => $currentState ? $cfg['color'] : '',
										'xSpaceBefore' => $currentState ? $cfg['xSpaceBefore'] : '',
										'xSpaceAfter' => $currentState ? $cfg['xSpaceAfter'] : '',
										'ySpaceBefore' => $currentState ? $cfg['ySpaceBefore'] : '',
										'ySpaceAfter' => $currentState ? $cfg['ySpaceAfter'] : '',
									);
								}
							}

								// Set the new result as result array:
							if (count($newResult))	{
								$result = $newResult;
							}
						}
					break;
				}
			}
		}

		return $result;
	}

	/**
	 * Calculates the spacing and wordSpacing values
	 *
	 * @param	array		TypoScript array for the TEXT GIFBUILDER object
	 * @param	integer		TypoScript value from eg $conf['niceText.']['scaleFactor']
	 * @return	array		Array with two keys [0]/[1] being array($spacing,$wordSpacing)
	 * @access private
	 * @see calcBBox()
	 */
	function calcWordSpacing($conf, $scaleFactor=1) {

		$spacing = intval($conf['spacing']);
		$wordSpacing = intval($conf['wordSpacing']);
		$wordSpacing = $wordSpacing?$wordSpacing:$spacing*2;

		$spacing*=$scaleFactor;
		$wordSpacing*=$scaleFactor;

		return array($spacing,$wordSpacing);
	}

	/**
	 * Calculates and returns the niceText.scaleFactor
	 *
	 * @param	array		TypoScript array for the TEXT GIFBUILDER object
	 * @return	integer		TypoScript value from eg $conf['niceText.']['scaleFactor']
	 * @access private
	 */
	function getTextScalFactor($conf) {
		if (!$conf['niceText']) {
			$sF = 1;
		} else {		// NICETEXT::
			$sF = t3lib_div::intInRange($conf['niceText.']['scaleFactor'],2,5);
		}
		return $sF;
	}











	/*********************************************
	 *
	 * Other GIFBUILDER objects related to TEXT
	 *
	 *********************************************/

	/**
	 * Implements the "OUTLINE" GIFBUILDER object / property for the TEXT object
	 *
	 * @param	pointer		GDlib image pointer
	 * @param	array		TypoScript array with configuration for the GIFBUILDER object.
	 * @param	array		The current working area coordinates.
	 * @param	array		TypoScript array with configuration for the associated TEXT GIFBUILDER object.
	 * @return	void
	 * @see tslib_gifBuilder::make(), makeText()
	 */
	function makeOutline(&$im,$conf,$workArea,$txtConf)	{
		$thickness = intval($conf['thickness']);
		if ($thickness)	{
			$txtConf['fontColor'] = $conf['color'];
			$outLineDist = t3lib_div::intInRange($thickness,1,2);
			for ($b=1;$b<=$outLineDist;$b++)	{
				if ($b==1)	{
					$it = 8;
				} else {
					$it = 16;
				}
				$outL = $this->circleOffset($b, $it);
				for ($a=0;$a<$it;$a++)	{
					$this->makeText($im,$txtConf,$this->applyOffset($workArea,$outL[$a]));
				}
			}
		}
	}

	/**
	 * Creates some offset values in an array used to simulate a circularly applied outline around TEXT
	 *
	 * access private
	 *
	 * @param	integer		Distance
	 * @param	integer		Iterations.
	 * @return	array
	 * @see makeOutline()
	 */
	function circleOffset($distance, $iterations)	{
		$res = Array();
		if ($distance && $iterations)	{
			for ($a=0;$a<$iterations;$a++)	{
				$yOff = round(sin(2*pi()/$iterations*($a+1))*100*$distance);
				if ($yOff)	{$yOff = intval(ceil(abs($yOff/100))*($yOff/abs($yOff)));}
				$xOff = round(cos(2*pi()/$iterations*($a+1))*100*$distance);
				if ($xOff)	{$xOff = intval(ceil(abs($xOff/100))*($xOff/abs($xOff)));}
				$res[$a] = Array($xOff,$yOff);
			}
		}
		return $res;
	}

	/**
	 * Implements the "EMBOSS" GIFBUILDER object / property for the TEXT object
	 *
	 * @param	pointer		GDlib image pointer
	 * @param	array		TypoScript array with configuration for the GIFBUILDER object.
	 * @param	array		The current working area coordinates.
	 * @param	array		TypoScript array with configuration for the associated TEXT GIFBUILDER object.
	 * @return	void
	 * @see tslib_gifBuilder::make(), makeShadow()
	 */
	function makeEmboss(&$im,$conf,$workArea,$txtConf)	{
		$conf['color']=$conf['highColor'];
		$this->makeShadow($im,$conf,$workArea,$txtConf);
		$newOffset = t3lib_div::intExplode(',',$conf['offset']);
		$newOffset[0]*=-1;
		$newOffset[1]*=-1;
		$conf['offset']=implode(',',$newOffset);
		$conf['color']=$conf['lowColor'];
		$this->makeShadow($im,$conf,$workArea,$txtConf);
	}

	/**
	 * Implements the "SHADOW" GIFBUILDER object / property for the TEXT object
	 * The operation involves ImageMagick for combining.
	 *
	 * @param	pointer		GDlib image pointer
	 * @param	array		TypoScript array with configuration for the GIFBUILDER object.
	 * @param	array		The current working area coordinates.
	 * @param	array		TypoScript array with configuration for the associated TEXT GIFBUILDER object.
	 * @return	void
	 * @see tslib_gifBuilder::make(), makeText(), makeEmboss()
	 */
	function makeShadow(&$im,$conf,$workArea,$txtConf)	{
		$workArea = $this->applyOffset($workArea,t3lib_div::intExplode(',',$conf['offset']));
		$blurRate = t3lib_div::intInRange(intval($conf['blur']),0,99);

		if (!$blurRate || $this->NO_IM_EFFECTS)	{		// No effects if ImageMagick ver. 5+
			$txtConf['fontColor'] = $conf['color'];
			$this->makeText($im,$txtConf,$workArea);
		} else {
			$w = imagesx($im);
			$h = imagesy($im);
			$blurBorder= 3;	// area around the blur used for cropping something
			$tmpStr = $this->randomName();
			$fileMenu = $tmpStr.'_menu.'.$this->gifExtension;
			$fileColor = $tmpStr.'_color.'.$this->gifExtension;
			$fileMask = $tmpStr.'_mask.'.$this->gifExtension;

				// BlurColor Image laves
			$blurColImg = $this->imagecreate($w,$h);
			$bcols=$this->convertColor($conf['color']);
			$Bcolor = ImageColorAllocate($blurColImg, $bcols[0],$bcols[1],$bcols[2]);
			ImageFilledRectangle($blurColImg, 0, 0, $w, $h, $Bcolor);
			$this->ImageWrite($blurColImg, $fileColor);
			ImageDestroy($blurColImg);

				// The mask is made: BlurTextImage
			$blurTextImg = $this->imagecreate($w+$blurBorder*2,$h+$blurBorder*2);
			$Bcolor = ImageColorAllocate($blurTextImg, 0,0,0);		// black background
			ImageFilledRectangle($blurTextImg, 0, 0, $w+$blurBorder*2, $h+$blurBorder*2, $Bcolor);
			$txtConf['fontColor'] = 'white';
			$blurBordArr = Array($blurBorder,$blurBorder);
			$this->makeText($blurTextImg,$txtConf,  $this->applyOffset($workArea,$blurBordArr));
			$this->ImageWrite($blurTextImg, $fileMask);	// dump to temporary file
			ImageDestroy($blurTextImg);	// destroy


			$command='';
			$command.=$this->maskNegate;

			if ($this->V5_EFFECTS)	{
				$command.=$this->v5_blur($blurRate+1);
			} else {
					// Blurring of the mask
				$times = ceil($blurRate/10);	// How many blur-commands that is executed. Min = 1;
				$newBlurRate = $blurRate*4;		// Here I boost the blur-rate so that it is 100 already at 25. The rest is done by up to 99 iterations of the blur-command.
				$newBlurRate = t3lib_div::intInRange($newBlurRate,1,99);
				for ($a=0;$a<$times;$a++)	{		// Building blur-command
					$command.=' -blur '.$blurRate;
				}
			}

			$this->imageMagickExec($fileMask,$fileMask,$command.' +matte');

			$blurTextImg_tmp = $this->imageCreateFromFile($fileMask);	// the mask is loaded again
			if ($blurTextImg_tmp)	{	// if nothing went wrong we continue with the blurred mask

					// cropping the border from the mask
				$blurTextImg = $this->imagecreate($w,$h);
				$this->imagecopyresized($blurTextImg, $blurTextImg_tmp, 0, 0, $blurBorder, $blurBorder, $w, $h, $w, $h);
				ImageDestroy($blurTextImg_tmp);	// Destroy the temporary mask

					// adjust the mask
				$intensity = 40;
				if ($conf['intensity'])	{
					$intensity = t3lib_div::intInRange($conf['intensity'],0,100);
				}
				$intensity = ceil(255-($intensity/100*255));
				$this->inputLevels($blurTextImg,0,$intensity,$this->maskNegate);

				$opacity = t3lib_div::intInRange(intval($conf['opacity']),0,100);
				if ($opacity && $opacity<100)	{
					$high = ceil(255*$opacity/100);
					$this->outputLevels($blurTextImg,0,$high,$this->maskNegate);	// reducing levels as the opacity demands
				}

				$this->ImageWrite($blurTextImg, $fileMask);	// Dump the mask again
				ImageDestroy($blurTextImg);	// Destroy the mask

					// The pictures are combined
				$this->ImageWrite($im, $fileMenu);	// The main pictures is saved temporarily

				$this->combineExec($fileMenu,$fileColor,$fileMask,$fileMenu);

				$backIm = $this->imageCreateFromFile($fileMenu);	// The main image is loaded again...
				if ($backIm)	{	// ... and if nothing went wrong we load it onto the old one.
					ImageColorTransparent($backIm,-1);
					$im = $backIm;
				}
			}
				// Deleting temporary files;
			if (!$this->dontUnlinkTempFiles)	{
				unlink($fileMenu);
				unlink($fileColor);
				unlink($fileMask);
			}
		}
	}





















	/****************************
	 *
	 * Other GIFBUILDER objects
	 *
	 ****************************/

	/**
	 * Implements the "BOX" GIFBUILDER object
	 *
	 * @param	pointer		GDlib image pointer
	 * @param	array		TypoScript array with configuration for the GIFBUILDER object.
	 * @param	array		The current working area coordinates.
	 * @return	void
	 * @see tslib_gifBuilder::make()
	 */
	function makeBox(&$im,$conf,$workArea)	{
		$cords = t3lib_div::intExplode(',',$conf['dimensions'].',,,');
		$conf['offset']=$cords[0].','.$cords[1];
		$cords = $this->objPosition($conf,$workArea,Array($cords[2],$cords[3]));
		$cols=$this->convertColor($conf['color']);
		if (!$this->truecolor)	{
			$reduce = t3lib_div::intInRange($this->setup['reduceColors'], 256, $this->truecolorColors, 256);
			$this->reduceColors($im, $reduce-1, $reduce-2);	// If "reduce-1" colors (or more) are used reduce them to "reduce-2"
		}
		$tmpColor = ImageColorAllocate($im, $cols[0],$cols[1],$cols[2]);
		imagefilledrectangle($im, $cords[0], $cords[1], $cords[0]+$cords[2]-1, $cords[1]+$cords[3]-1, $tmpColor);
	}

	/**
	 * Implements the "EFFECT" GIFBUILDER object
	 * The operation involves ImageMagick for applying effects
	 *
	 * @param	pointer		GDlib image pointer
	 * @param	array		TypoScript array with configuration for the GIFBUILDER object.
	 * @return	void
	 * @see tslib_gifBuilder::make(), applyImageMagickToPHPGif()
	 */
	function makeEffect(&$im, $conf)	{
		$commands = $this->IMparams($conf['value']);
		if ($commands)	{
			$this->applyImageMagickToPHPGif($im, $commands);
		}
	}

	/**
	 * Creating ImageMagick paramters from TypoScript property
	 *
	 * @param	string		A string with effect keywords=value pairs separated by "|"
	 * @return	string		ImageMagick prepared parameters.
	 * @access private
	 * @see makeEffect()
	 */
	function IMparams($setup)	{
		if (!trim($setup)){return '';}
		$effects = explode('|', $setup);
		$commands = '';
		while(list(,$val)=each($effects))	{
			$pairs=explode('=',$val,2);
			$value = trim($pairs[1]);
			$effect = strtolower(trim($pairs[0]));
			switch($effect)	{
				case 'gamma':
					$commands.=' -gamma '.doubleval($value);
				break;
				case 'blur':
					if (!$this->NO_IM_EFFECTS)	{
						if ($this->V5_EFFECTS)	{
							$commands.=$this->v5_blur($value);
						} else {
							$commands.=' -blur '.t3lib_div::intInRange($value,1,99);
						}
					}
				break;
				case 'sharpen':
					if (!$this->NO_IM_EFFECTS)	{
						if ($this->V5_EFFECTS)	{
							$commands.=$this->v5_sharpen($value);
						} else {
							$commands.=' -sharpen '.t3lib_div::intInRange($value,1,99);
						}
					}
				break;
				case 'rotate':
					$commands.=' -rotate '.t3lib_div::intInRange($value,0,360);
				break;
				case 'solarize':
					$commands.=' -solarize '.t3lib_div::intInRange($value,0,99);
				break;
				case 'swirl':
					$commands.=' -swirl '.t3lib_div::intInRange($value,0,1000);
				break;
				case 'wave':
					$params = t3lib_div::intExplode(',',$value);
					$commands.=' -wave '.t3lib_div::intInRange($params[0],0,99).'x'.t3lib_div::intInRange($params[1],0,99);
				break;
				case 'charcoal':
					$commands.=' -charcoal '.t3lib_div::intInRange($value,0,100);
				break;
				case 'gray':
					$commands.=' -colorspace GRAY';
				break;
				case 'edge':
					$commands.=' -edge '.t3lib_div::intInRange($value,0,99);
				break;
				case 'emboss':
					$commands.=' -emboss';
				break;
				case 'flip':
					$commands.=' -flip';
				break;
				case 'flop':
					$commands.=' -flop';
				break;
				case 'colors':
					$commands.=' -colors '.t3lib_div::intInRange($value,2,255);
				break;
				case 'shear':
					$commands.=' -shear '.t3lib_div::intInRange($value,-90,90);
				break;
				case 'invert':
					$commands.=' -negate';
				break;
			}
		}
		return $commands;
	}

	/**
	 * Implements the "ADJUST" GIFBUILDER object
	 *
	 * @param	pointer		GDlib image pointer
	 * @param	array		TypoScript array with configuration for the GIFBUILDER object.
	 * @return	void
	 * @see tslib_gifBuilder::make(), autoLevels(), outputLevels(), inputLevels()
	 */
	function adjust(&$im, $conf)	{
		$setup = $conf['value'];
		if (!trim($setup)){return '';}
		$effects = explode('|', $setup);
		while(list(,$val)=each($effects))	{
			$pairs=explode('=',$val,2);
			$value = trim($pairs[1]);
			$effect = strtolower(trim($pairs[0]));
			switch($effect)	{
				case 'inputlevels':	// low,high
					$params = t3lib_div::intExplode(',',$value);
					$this->inputLevels($im,$params[0],$params[1]);
				break;
				case 'outputlevels':
					$params = t3lib_div::intExplode(',',$value);
					$this->outputLevels($im,$params[0],$params[1]);
				break;
				case 'autolevels':
					$this->autoLevels($im);
				break;
			}
		}
	}

	/**
	 * Implements the "CROP" GIFBUILDER object
	 *
	 * @param	pointer		GDlib image pointer
	 * @param	array		TypoScript array with configuration for the GIFBUILDER object.
	 * @return	void
	 * @see tslib_gifBuilder::make()
	 */
	function crop(&$im,$conf)	{
		$this->setWorkArea('');	// clears workArea to total image
		$cords = t3lib_div::intExplode(',',$conf['crop'].',,,');
		$conf['offset']=$cords[0].','.$cords[1];
		$cords = $this->objPosition($conf,$this->workArea,Array($cords[2],$cords[3]));

		$newIm = $this->imagecreate($cords[2],$cords[3]);
		$cols=$this->convertColor($conf['backColor']?$conf['backColor']:$this->setup['backColor']);
		$Bcolor = ImageColorAllocate($newIm, $cols[0],$cols[1],$cols[2]);
		ImageFilledRectangle($newIm, 0, 0, $cords[2], $cords[3], $Bcolor);

		$newConf = Array();
		$workArea = Array(0,0,$cords[2],$cords[3]);
		if ($cords[0]<0) {$workArea[0]=abs($cords[0]);} else {$newConf['offset']=-$cords[0];}
		if ($cords[1]<0) {$workArea[1]=abs($cords[1]);} else {$newConf['offset'].=','.-$cords[1];}

		$this->copyGifOntoGif($newIm,$im,$newConf,$workArea);
		$im = $newIm;
		$this->w = imagesx($im);
		$this->h = imagesy($im);
		$this->setWorkArea('');	// clears workArea to total image
	}

	/**
	 * Implements the "SCALE" GIFBUILDER object
	 *
	 * @param	pointer		GDlib image pointer
	 * @param	array		TypoScript array with configuration for the GIFBUILDER object.
	 * @return	void
	 * @see tslib_gifBuilder::make()
	 */
	function scale(&$im,$conf)	{
		if ($conf['width'] || $conf['height'] || $conf['params'])	{
			$tmpStr = $this->randomName();
			$theFile = $tmpStr.'.'.$this->gifExtension;
			$this->ImageWrite($im, $theFile);
			$theNewFile = $this->imageMagickConvert($theFile,$this->gifExtension,$conf['width'],$conf['height'],$conf['params'],'','');
			$tmpImg = $this->imageCreateFromFile($theNewFile[3]);
			if ($tmpImg)	{
				ImageDestroy($im);
				$im = $tmpImg;
				$this->w = imagesx($im);
				$this->h = imagesy($im);
				$this->setWorkArea('');	// clears workArea to total image
			}
			if (!$this->dontUnlinkTempFiles)	{
				unlink($theFile);
				if ($theNewFile[3] && $theNewFile[3]!=$theFile)	{
					unlink($theNewFile[3]);
				}
			}
		}
	}

	/**
	 * Implements the "WORKAREA" GIFBUILDER object when setting it
	 * Setting internal working area boundaries (->workArea)
	 *
	 * @param	string		Working area dimensions, comma separated
	 * @return	void
	 * @access private
	 * @see tslib_gifBuilder::make()
	 */
	function setWorkArea($workArea)	{
		$this->workArea = t3lib_div::intExplode(',',$workArea);
		$this->workArea = $this->applyOffset($this->workArea,$this->OFFSET);
		if (!$this->workArea[2])	{$this->workArea[2]=$this->w;}
		if (!$this->workArea[3])	{$this->workArea[3]=$this->h;}
	}























	/*************************
	 *
	 * Adjustment functions
	 *
	 ************************/

	/**
	 * Apply auto-levels to input image pointer
	 *
	 * @param	integer		GDlib Image Pointer
	 * @return	void
	 */
	function autolevels(&$im)	{
		$totalCols = ImageColorsTotal($im);
		$min=255;
		$max=0;
		for ($c=0; $c<$totalCols; $c++)	{
			$cols = ImageColorsForIndex($im,$c);
			$grayArr[] = round(($cols['red']+$cols['green']+$cols['blue'])/3);
		}
		$min=min($grayArr);
		$max=max($grayArr);
		$delta = $max-$min;
		if ($delta)	{
			for ($c=0; $c<$totalCols; $c++)	{
				$cols = ImageColorsForIndex($im,$c);
				$cols['red'] = floor(($cols['red']-$min)/$delta*255);
				$cols['green'] = floor(($cols['green']-$min)/$delta*255);
				$cols['blue'] = floor(($cols['blue']-$min)/$delta*255);
				ImageColorSet($im,$c,$cols['red'],$cols['green'],$cols['blue']);
			}
		}
	}

	/**
	 * Apply output levels to input image pointer (decreasing contrast)
	 *
	 * @param	integer		GDlib Image Pointer
	 * @param	integer		The "low" value (close to 0)
	 * @param	integer		The "high" value (close to 255)
	 * @param	boolean		If swap, then low and high are swapped. (Useful for negated masks...)
	 * @return	void
	 */
	function outputLevels(&$im,$low,$high,$swap='')	{
		if ($low<$high){
			$low = t3lib_div::intInRange($low,0,255);
			$high = t3lib_div::intInRange($high,0,255);

			if ($swap)	{
				$temp = $low;
				$low = 255-$high;
				$high = 255-$temp;
			}

			$delta = $high-$low;
			$totalCols = ImageColorsTotal($im);
			for ($c=0; $c<$totalCols; $c++)	{
				$cols = ImageColorsForIndex($im,$c);
				$cols['red'] = $low+floor($cols['red']/255*$delta);
				$cols['green'] = $low+floor($cols['green']/255*$delta);
				$cols['blue'] = $low+floor($cols['blue']/255*$delta);
				ImageColorSet($im,$c,$cols['red'],$cols['green'],$cols['blue']);
			}
		}
	}

	/**
	 * Apply input levels to input image pointer (increasing contrast)
	 *
	 * @param	integer		GDlib Image Pointer
	 * @param	integer		The "low" value (close to 0)
	 * @param	integer		The "high" value (close to 255)
	 * @param	boolean		If swap, then low and high are swapped. (Useful for negated masks...)
	 * @return	void
	 */
	function inputLevels(&$im,$low,$high,$swap='')	{
		if ($low<$high){
			$low = t3lib_div::intInRange($low,0,255);
			$high = t3lib_div::intInRange($high,0,255);

			if ($swap)	{
				$temp = $low;
				$low = 255-$high;
				$high = 255-$temp;
			}

			$delta = $high-$low;
			$totalCols = ImageColorsTotal($im);
			for ($c=0; $c<$totalCols; $c++)	{
				$cols = ImageColorsForIndex($im,$c);
				$cols['red'] = t3lib_div::intInRange(($cols['red']-$low)/$delta*255, 0,255);
				$cols['green'] = t3lib_div::intInRange(($cols['green']-$low)/$delta*255, 0,255);
				$cols['blue'] = t3lib_div::intInRange(($cols['blue']-$low)/$delta*255, 0,255);
				ImageColorSet($im,$c,$cols['red'],$cols['green'],$cols['blue']);
			}
		}
	}

	/**
	 * Reduce colors in image dependend on the actual amount of colors (Only works if we are not in truecolor mode)
	 *
	 * @param	integer		GDlib Image Pointer
	 * @param	integer		The max number of colors in the image before a reduction will happen; basically this means that IF the GD image current has the same amount or more colors than $limit define, THEN a reduction is performed.
	 * @param	integer		Number of colors to reduce the image to.
	 * @return	void
	 */
	function reduceColors(&$im,$limit, $cols)	{
		if (!$this->truecolor && ImageColorsTotal($im)>=$limit)	{
			$this->makeEffect($im, Array('value'=>'colors='.$cols) );
		}
	}

	/**
	 * Reduce colors in image using IM and create a palette based image if possible (<=256 colors)
	 *
	 * @param	string		Image file to reduce
	 * @param	integer		Number of colors to reduce the image to.
	 * @return	string		Reduced file
	 */
	function IMreduceColors($file, $cols)	{
		$fI = t3lib_div::split_fileref($file);
		$ext = strtolower($fI['fileext']);
		$result = $this->randomName().'.'.$ext;
		if (($reduce = t3lib_div::intInRange($cols, 0, ($ext=='gif'?256:$this->truecolorColors), 0))>0)	{
			$params = ' -colors '.$reduce;
			if (!$this->im_version_4)	{
					// IM4 doesn't have this options but forces them automatically if applicaple (<256 colors in image)
				if ($reduce<=256)	{ $params .= ' -type Palette'; }
				if ($ext=='png' && $reduce<=256)	{ $prefix = 'png8:'; }
			}
			$this->imageMagickExec($file, $prefix.$result, $params);
			if ($result)	{
				return $result;
			}
		}
		return '';
	}











	/*********************************
	 *
	 * GIFBUILDER Helper functions
	 *
	 *********************************/

	/**
	 * Checks if the $fontFile is already at an absolute path and if not, prepends the correct path.
	 * Use PATH_site unless we are in the backend.
	 * Call it by t3lib_stdGraphic::prependAbsolutePath()
	 *
	 * @param	string		The font file
	 * @return	string		The font file with absolute path.
	 */
	function prependAbsolutePath($fontFile)	{
		$absPath = defined('PATH_typo3') ? dirname(PATH_thisScript).'/' :PATH_site;
		$fontFile = t3lib_div::isAbsPath($fontFile) ? $fontFile : t3lib_div::resolveBackPath($absPath.$fontFile);
		return $fontFile;
	}

	/**
	 * Returns the IM command for sharpening with ImageMagick 5 (when $this->V5_EFFECTS is set).
	 * Uses $this->im5fx_sharpenSteps for translation of the factor to an actual command.
	 *
	 * @param	integer		The sharpening factor, 0-100 (effectively in 10 steps)
	 * @return	string		The sharpening command, eg. " -sharpen 3x4"
	 * @see makeText(), IMparams(), v5_blur()
	 */
	function v5_sharpen($factor)	{
		$factor = t3lib_div::intInRange(ceil($factor/10),0,10);

		$sharpenArr=explode(',',','.$this->im5fx_sharpenSteps);
		$sharpenF= trim($sharpenArr[$factor]);
		if ($sharpenF)	{
			$cmd = ' -sharpen '.$sharpenF;
			return $cmd;
		}
	}

	/**
	 * Returns the IM command for blurring with ImageMagick 5 (when $this->V5_EFFECTS is set).
	 * Uses $this->im5fx_blurSteps for translation of the factor to an actual command.
	 *
	 * @param	integer		The blurring factor, 0-100 (effectively in 10 steps)
	 * @return	string		The blurring command, eg. " -blur 3x4"
	 * @see makeText(), IMparams(), v5_sharpen()
	 */
	function v5_blur($factor)	{
		$factor = t3lib_div::intInRange(ceil($factor/10),0,10);

		$blurArr=explode(',',','.$this->im5fx_blurSteps);
		$blurF= trim($blurArr[$factor]);
		if ($blurF)	{
			$cmd=' -blur '.$blurF;
			return $cmd;
		}
	}

	/**
	 * Returns a random filename prefixed with "temp_" and then 32 char md5 hash (without extension) from $this->tempPath.
	 * Used by functions in this class to create truely temporary files for the on-the-fly processing. These files will most likely be deleted right away.
	 *
	 * @return	string
	 */
	function randomName()	{
		$this->createTempSubDir('temp/');
		return $this->tempPath.'temp/'.md5(uniqid(''));
	}

	/**
	 * Applies offset value to coordinated in $cords.
	 * Basically the value of key 0/1 of $OFFSET is added to keys 0/1 of $cords
	 *
	 * @param	array		Integer coordinates in key 0/1
	 * @param	array		Offset values in key 0/1
	 * @return	array		Modified $cords array
	 */
	function applyOffset($cords,$OFFSET)	{
		$cords[0] = intval($cords[0])+intval($OFFSET[0]);
		$cords[1] = intval($cords[1])+intval($OFFSET[1]);
		return $cords;
	}

	/**
	 * Converts a "HTML-color" TypoScript datatype to RGB-values.
	 * Default is 0,0,0
	 *
	 * @param	string		"HTML-color" data type string, eg. 'red', '#ffeedd' or '255,0,255'. You can also add a modifying operator afterwards. There are two options: "255,0,255 : 20" - will add 20 to values, result is "255,20,255". Or "255,0,255 : *1.23" which will multiply all RGB values with 1.23
	 * @return	array		RGB values in key 0/1/2 of the array
	 */
	function convertColor($string)	{
		$col=array();
		$cParts = explode(':',$string,2);

			// Finding the RGB definitions of the color:
		$string=$cParts[0];
		if (strstr($string,'#'))	{
			$string = ereg_replace('[^A-Fa-f0-9]*','',$string);
			$col[]=HexDec(substr($string,0,2));
			$col[]=HexDec(substr($string,2,2));
			$col[]=HexDec(substr($string,4,2));
		} elseif (strstr($string,','))	{
			$string = ereg_replace('[^,0-9]*','',$string);
			$strArr = explode(',',$string);
			$col[]=intval($strArr[0]);
			$col[]=intval($strArr[1]);
			$col[]=intval($strArr[2]);
		} else {
			$string = strtolower(trim($string));
			if ($this->colMap[$string])	{
				$col = $this->colMap[$string];
			} else {
				$col = Array(0,0,0);
			}
		}
			// ... and possibly recalculating the value
		if (trim($cParts[1]))	{
			$cParts[1]=trim($cParts[1]);
			if (substr($cParts[1],0,1)=='*')	{
				$val=doubleval(substr($cParts[1],1));
				$col[0]=t3lib_div::intInRange($col[0]*$val,0,255);
				$col[1]=t3lib_div::intInRange($col[1]*$val,0,255);
				$col[2]=t3lib_div::intInRange($col[2]*$val,0,255);
			} else {
				$val=intval($cParts[1]);
				$col[0]=t3lib_div::intInRange($col[0]+$val,0,255);
				$col[1]=t3lib_div::intInRange($col[1]+$val,0,255);
				$col[2]=t3lib_div::intInRange($col[2]+$val,0,255);
			}
		}
		return $col;
	}

	/**
	 * Recode string
	 * Used with text strings for fonts when languages has other character sets.
	 *
	 * @param	string		The text to recode
	 * @return	string		The recoded string. Should be UTF-8 output. MAY contain entities (eg. &#123; or &#quot; which should render as real chars).
	 */
	function recodeString($string)	{
			// Recode string to UTF-8 from $this->nativeCharset:
		if ($this->nativeCharset && $this->nativeCharset!='utf-8')	{
			$string = $this->csConvObj->utf8_encode($string,$this->nativeCharset);	// Convert to UTF-8
		}

			// Recode string accoding to TTFLocaleConv. Deprecated.
		if ($this->TTFLocaleConv)	{
			$string = recode_string($this->TTFLocaleConv,$string);
		}

		return $string;
	}

	/**
	 * Split a string into an array of individual characters
	 * The function will look at $this->nativeCharset and if that is set, the input string is expected to be UTF-8 encoded, possibly with entities in it. Otherwise the string is supposed to be a single-byte charset which is just splitted by a for-loop.
	 *
	 * @param	string		The text string to split
	 * @param	boolean		Return Unicode numbers instead of chars.
	 * @return	array		Numerical array with a char as each value.
	 */
	function singleChars($theText,$returnUnicodeNumber=FALSE)	{
		if ($this->nativeCharset)	{
			return $this->csConvObj->utf8_to_numberarray($theText,1,$returnUnicodeNumber ? 0 : 1);	// Get an array of separated UTF-8 chars
		} else {
			$output=array();
			$c=strlen($theText);
			for($a=0;$a<$c;$a++)	{
				$output[]=substr($theText,$a,1);
			}
			return $output;
		}
	}

	/**
	 * Create an array with object position/boundaries based on input TypoScript configuration (such as the "align" property is used), the work area definition and $BB array
	 *
	 * @param	array		TypoScript configuration for a GIFBUILDER object
	 * @param	array		Workarea definition
	 * @param	array		BB (Bounding box) array. Not just used for TEXT objects but also for others
	 * @return	array		[0]=x, [1]=y, [2]=w, [3]=h
	 * @access private
	 * @see copyGifOntoGif(), makeBox(), crop()
	 */
	function objPosition($conf,$workArea,$BB) {
			// offset, align, valign, workarea
		$result=Array();
		$result[2] = $BB[0];
		$result[3] = $BB[1];
		$w=$workArea[2];
		$h=$workArea[3];

		$align = explode(',',$conf['align']);
		$align[0] = strtolower(substr(trim($align[0]),0,1));
		$align[1] = strtolower(substr(trim($align[1]),0,1));

		switch($align[0])	{
			case 'r':
				$result[0]=$w-$result[2];
			break;
			case 'c':
				$result[0] = round(($w-$result[2])/2);
			break;
			default:
				$result[0] = 0;
			break;
		}
		switch($align[1])	{
			case 'b':
				$result[1] = $h-$result[3];	// y pos
			break;
			case 'c':
				$result[1] = round(($h-$result[3])/2);
			break;
			default:
				$result[1]=0;
			break;
		}
		$result = $this->applyOffset($result,t3lib_div::intExplode(',',$conf['offset']));
		$result = $this->applyOffset($result,$workArea);
		return $result;
	}





















	/***********************************
	 *
	 * Scaling, Dimensions of images
	 *
	 ***********************************/

	/**
	 * Converts $imagefile to another file in temp-dir of type $newExt (extension).
	 *
	 * @param	string		The image filepath
	 * @param	string		New extension, eg. "gif", "png", "jpg", "tif". If $newExt is NOT set, the new imagefile will be of the original format. If newExt = 'WEB' then one of the web-formats is applied.
	 * @param	string		Width. $w / $h is optional. If only one is given the image is scaled proportionally. If an 'm' exists in the $w or $h and if both are present the $w and $h is regarded as the Maximum w/h and the proportions will be kept
	 * @param	string		Height. See $w
	 * @param	string		Additional ImageMagick parameters.
	 * @param	string		Refers to which frame-number to select in the image. '' or 0 will select the first frame, 1 will select the next and so on...
	 * @param	array		An array with options passed to getImageScale (see this function).
	 * @param	boolean		If set, then another image than the input imagefile MUST be returned. Otherwise you can risk that the input image is good enough regarding messures etc and is of course not rendered to a new, temporary file in typo3temp/. But this option will force it to.
	 * @return	array		[0]/[1] is w/h, [2] is file extension and [3] is the filename.
	 * @see getImageScale(), typo3/show_item.php, fileList_ext::renderImage(), tslib_cObj::getImgResource(), SC_tslib_showpic::show(), maskImageOntoImage(), copyImageOntoImage(), scale()
	 */
	function imageMagickConvert($imagefile,$newExt='',$w='',$h='',$params='',$frame='',$options='',$mustCreate=0)	{
		if ($this->NO_IMAGE_MAGICK)	{
				// Returning file info right away
			return $this->getImageDimensions($imagefile);
		}

		if($info=$this->getImageDimensions($imagefile))	{
			$newExt=strtolower(trim($newExt));
			if (!$newExt)	{	// If no extension is given the original extension is used
				$newExt = $info[2];
			}
			if ($newExt=='web')	{
				if (t3lib_div::inList($this->webImageExt,$info[2]))	{
					$newExt = $info[2];
				} else {
					$newExt = $this->gif_or_jpg($info[2],$info[0],$info[1]);
					if (!$params)	{
						$params = $this->cmds[$newExt];
					}
				}
			}
			if (t3lib_div::inList($this->imageFileExt,$newExt))	{
				if (strstr($w.$h, 'm')) {$max=1;} else {$max=0;}

				$data = $this->getImageScale($info,$w,$h,$options);
				$w=$data['origW'];
				$h=$data['origH'];

					// if no convertion should be performed
				$wh_noscale = (!$w && !$h) || ($data[0]==$info[0] && $data[1]==$info[1]);		// this flag is true if the width / height does NOT dictate the image to be scaled!! (that is if no w/h is given or if the destination w/h matches the original image-dimensions....

				if ($wh_noscale && !$data['crs'] && !$params && !$frame && $newExt==$info[2] && !$mustCreate) {
					$info[3] = $imagefile;
					return $info;
				}
				$info[0]=$data[0];
				$info[1]=$data[1];

				$frame = $this->noFramePrepended ? '' : '['.intval($frame).']';

				if (!$params)	{
					$params = $this->cmds[$newExt];
				}

				$command = $this->scalecmd.' '.$info[0].'x'.$info[1].'! '.$params.' ';
				$cropscale = ($data['crs'] ? 'crs-V'.$data['cropV'].'H'.$data['cropH'] : '');

				if ($this->alternativeOutputKey)	{
					$theOutputName = t3lib_div::shortMD5($command.$cropscale.basename($imagefile).$this->alternativeOutputKey.$frame);
				} else {
					$theOutputName = t3lib_div::shortMD5($command.$cropscale.$imagefile.filemtime($imagefile).$frame);
				}
				if ($this->imageMagickConvert_forceFileNameBody)	{
					$theOutputName = $this->imageMagickConvert_forceFileNameBody;
					$this->imageMagickConvert_forceFileNameBody='';
				}

					// Making the temporary filename:
				$this->createTempSubDir('pics/');
				$output = $this->absPrefix.$this->tempPath.'pics/'.$this->filenamePrefix.$theOutputName.'.'.$newExt;

					// Register temporary filename:
				$GLOBALS['TEMP_IMAGES_ON_PAGE'][] = $output;

					// Cropscaling:
				if ($data['crs'])	{
					if ($this->dontCheckForExistingTempFile || !$this->file_exists_typo3temp_file($output, $imagefile))	{
						$crsOutput = str_replace('pics/', 'pics/crs-', $output);
						$this->imageMagickExec($imagefile.$frame, $crsOutput, $command);
						$gifCreator = t3lib_div::makeInstance('tslib_gifbuilder');
						$gifCreator->init();
						if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['gdlib'] !== 0)	{
							if (!$data['origW']) { $data['origW'] = $data[0]; }
							if (!$data['origH']) { $data['origH'] = $data[1]; }
							$ofX = intval(($data['origW'] - $data[0]) * ($data['cropH']+100)/200);
							$ofY = intval(($data['origH'] - $data[1]) * ($data['cropV']+100)/200);
							$tmpParm = Array('XY' => intval($data['origW']).','.intval($data['origH']),
									'10' => 'IMAGE',
									'10.' => array('file'=> $crsOutput, 'offset'=> $ofX.','.$ofY),
							);
							$gifCreator->start($tmpParm, array());
							$newoutput = $gifCreator->gifBuild();
							if (!copy($newoutput,$output)) {
								$output = $newoutput;
							}
						} else {
							$output = $crsOutput;
						}
					}
				} elseif ($this->dontCheckForExistingTempFile || !$this->file_exists_typo3temp_file($output,$imagefile)) {
					$this->imageMagickExec($imagefile.$frame,$output,$command);
				}
				if (@file_exists($output))	{
					$info[3] = $output;
					$info[2] = $newExt;
					if ($params)	{	// params could realisticly change some imagedata!
						$info=$this->getImageDimensions($info[3]);
					}
					if ($info[2]==$this->gifExtension && !$this->dontCompress)	{
						t3lib_div::gif_compress($info[3],'');		// Compress with IM (lzw) or GD (rle)  (Workaround for the absence of lzw-compression in GD)
					}
					return $info;
				}
			}
		}
	}

	/**
	 * Gets the input image dimensions.
	 *
	 * @param	string		The image filepath
	 * @return	array		Returns an array where [0]/[1] is w/h, [2] is extension and [3] is the filename.
	 * @see imageMagickConvert(), tslib_cObj::getImgResource()
	 */
	function getImageDimensions($imageFile)	{
		ereg('([^\.]*)$',$imageFile,$reg);
		if (@file_exists($imageFile) && t3lib_div::inList($this->imageFileExt,strtolower($reg[0])))	{
			if ($returnArr = $this->getCachedImageDimensions($imageFile))	{
				return $returnArr;
			} else {
				if ($temp = @getImageSize($imageFile))	{
					$returnArr = Array($temp[0], $temp[1], strtolower($reg[0]), $imageFile);
				} else {
					$returnArr = $this->imageMagickIdentify($imageFile);
				}
				if ($returnArr) {
					$this->cacheImageDimensions($returnArr);
					return $returnArr;
				}
			}
		}
		return false;
	}

	/**
	 * Cache the result of the getImageDimensions function into the database. Does not check if the
	 * file exists!
	 *
	 * @param	array		$identifyResult: Result of the getImageDimensions function
	 * @return	boolean		True if operation was successful
	 * @author	Michael Stucki <michael@typo3.org> / Robert Lemke <rl@robertlemke.de>
	 */
	function cacheImageDimensions($identifyResult)	{
		global $TYPO3_DB;
			// Create a md5 hash of the filename
		if (function_exists('md5_file')) {
			$md5Hash = md5_file($identifyResult[3]);
		} else {
			$md5Hash = md5 (t3lib_div::getURL($identifyResult[3]));
		}
		if ($md5Hash) {
			$fieldArr = array (
				'md5hash' => $md5Hash,
				'md5filename' => md5($identifyResult[3]),
				'tstamp' => time(),
				'filename' => $identifyResult[3],
				'imagewidth' => $identifyResult[0],
				'imageheight' => $identifyResult[1],
			);
			$TYPO3_DB->exec_INSERTquery('cache_imagesizes', $fieldArr);
			if (!$err = $TYPO3_DB->sql_error())	{
				return true;
			}
		}
		return false;
	}

	/**
	 * Fetch the cached imageDimensions from the MySQL database. Does not check if the image file exists!
	 *
	 * @param	string		The image filepath
	 * @return	array		Returns an array where [0]/[1] is w/h, [2] is extension and [3] is the filename.
	 * @author	Michael Stucki <michael@typo3.org> / Robert Lemke <rl@robertlemke.de>
	 */
	function getCachedImageDimensions($imageFile)	{
		global $TYPO3_DB;
			// Create a md5 hash of the filename
		if(function_exists('md5_file')) {
			$md5Hash = md5_file($imageFile);
		} else {
			$md5Hash = md5(t3lib_div::getURL ($imageFile));
		}
		ereg('([^\.]*)$',$imageFile,$reg);
		$res = $TYPO3_DB->exec_SELECTquery ('md5hash, imagewidth, imageheight', 'cache_imagesizes', 'md5filename='.$TYPO3_DB->fullQuoteStr(md5($imageFile),'cache_imagesizes'));
		if ($res) {
			if ($row = $TYPO3_DB->sql_fetch_assoc($res)) {
				if ($row['md5hash']!=$md5Hash) {
						// file has changed, delete the row
					$TYPO3_DB->exec_DELETEquery ('cache_imagesizes', 'md5hash='.$TYPO3_DB->fullQuoteStr($row['md5hash'],'cache_imagesizes'));
				} else {
					return (array($row['imagewidth'], $row['imageheight'], strtolower($reg[0]), $imageFile));
				}
			}
		}
		return false;
	}

	/**
	 * Get numbers for scaling the image based on input
	 *
	 * @param	array		Current image information: Width, Height etc.
	 * @param	integer		"required" width
	 * @param	integer		"required" height
	 * @param	array		Options: Keys are like "maxW", "maxH", "minW", "minH"
	 * @return	array
	 * @access private
	 * @see imageMagickConvert()
	 */
	function getImageScale($info,$w,$h,$options) {
		if (strstr($w.$h, 'm')) {$max=1;} else {$max=0;}

		if (strstr($w.$h, 'c')) {
			$out['cropH'] = intval(substr(strstr($w, 'c'), 1));
			$out['cropV'] = intval(substr(strstr($h, 'c'), 1));
			$crs = true;
		} else {
			$crs = false;
		}
		$out['crs'] = $crs;

		$w=intval($w);
		$h=intval($h);
			// if there are max-values...
		if ($options['maxW'])	{
			if ($w) {	// if width is given...
				if ($w>$options['maxW']) {
					$w=$options['maxW'];
					$max=1;	// height should follow
				}
			} else {
				if ($info[0]>$options['maxW']) {
					$w=$options['maxW'];
					$max=1; // height should follow
				}
			}
		}
		if ($options['maxH'])	{
			if ($h) {	// if height is given...
				if ($h>$options['maxH']) {
					$h=$options['maxH'];
					$max=1;	// height should follow
				}
			} else {
				if ($info[1]>$options['maxH']) {	// Changed [0] to [1] 290801
					$h=$options['maxH'];
					$max=1; // height should follow
				}
			}
		}
		$out['origW']=$w;
		$out['origH']=$h;
		$out['max'] = $max;

		if (!$this->mayScaleUp) {
			if ($w>$info[0]){$w=$info[0];}
			if ($h>$info[1]){$h=$info[1];}
		}
		if ($w || $h)	{	// if scaling should be performed
			if ($w && !$h)	{
				$info[1] = ceil($info[1]*($w/$info[0]));
				$info[0] = $w;
			}
			if (!$w && $h)	{
				$info[0] = ceil($info[0]*($h/$info[1]));
				$info[1] = $h;
			}
			if ($w && $h)	{
				if ($max)	{
					$ratio = $info[0]/$info[1];
					if ($h*$ratio > $w) {
						$h = round($w/$ratio);
					} else {
						$w = round($h*$ratio);
					}
				}
				if ($crs)	{
					$ratio = $info[0] / $info[1];
					if ($h * $ratio < $w) {
						$h = round($w / $ratio);
					} else {
						$w = round($h * $ratio);
					}
				}
				$info[0] = $w;
				$info[1] = $h;
			}
		}
		$out[0]=$info[0];
		$out[1]=$info[1];
			// Set minimum-measures!
		if ($options['minW'] && $out[0]<$options['minW'])	{
			if (($max || $crs) && $out[0])	{
				$out[1]= round($out[1]*$options['minW']/$out[0]);
			}
			$out[0]=$options['minW'];
		}
		if ($options['minH'] && $out[1]<$options['minH'])	{
			if (($max || $crs) && $out[1])	{
				$out[0]= round($out[0]*$options['minH']/$out[1]);
			}
			$out[1]=$options['minH'];
		}

		return $out;
	}

	/**
	 * Used to check if a certain process of scaling an image is already being carried out (can be logged in the SQL database)
	 *
	 * @param	string		Output imagefile
	 * @param	string		Original basis file
	 * @return	boolean		Returns true if the file is already being made; thus "true" means "Don't render the image again"
	 * @access private
	 */
	function file_exists_typo3temp_file($output,$orig='')	{
		if ($this->enable_typo3temp_db_tracking)	{
			if (@file_exists($output))	{	// If file exists, then we return immediately
				return 1;
			} else {	// If not, we look up in the cache_typo3temp_log table to see if there is a image being rendered right now.
				$md5Hash=md5($output);
				$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('md5hash', 'cache_typo3temp_log', 'md5hash='.$GLOBALS['TYPO3_DB']->fullQuoteStr($md5Hash, 'cache_typo3temp_log').' AND tstamp>'.(time()-30));
				if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))	{	// If there was a record, the image is being generated by another proces (we assume)
					if (is_object($GLOBALS['TSFE']))	$GLOBALS['TSFE']->set_no_cache();	// ...so we set no_cache, because we dont want this page (which will NOT display an image...!) to be cached! (Only a page with the correct image on...)
					if (is_object($GLOBALS['TT']))	$GLOBALS['TT']->setTSlogMessage('typo3temp_log: Assume this file is being rendered now: '.$output);
					return 2;	// Return 'success - 2'
				} else {		// If the current time is more than 30 seconds since this record was written, we clear the record, write a new and render the image.

					$insertFields = array(
						'md5hash' => $md5Hash,
						'tstamp' => time(),
						'filename' => $output,
						'orig_filename' => $orig
					);
					$GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_typo3temp_log', 'md5hash='.$GLOBALS['TYPO3_DB']->fullQuoteStr($md5Hash, 'cache_typo3temp_log'));
					$GLOBALS['TYPO3_DB']->exec_INSERTquery('cache_typo3temp_log', $insertFields);

					if (is_object($GLOBALS['TT']))	$GLOBALS['TT']->setTSlogMessage('typo3temp_log: The row did not exist, so a new is written and file is being processed: '.$output);
					return 0;
				}
			}
		} else {
			return @file_exists($output);
		}
	}


















	/***********************************
	 *
	 * ImageMagick API functions
	 *
	 ***********************************/

	/**
	 * Returns an array where [0]/[1] is w/h, [2] is extension and [3] is the filename.
	 * Using ImageMagick
	 *
	 * @param	string		The relative (to PATH_site) image filepath
	 * @return	array
	 */
	function imageMagickIdentify($imagefile)	{
		if (!$this->NO_IMAGE_MAGICK)	{
			$frame = $this->noFramePrepended?'':'[0]';
			$cmd = t3lib_div::imageMagickCommand('identify', $this->wrapFileName($imagefile).$frame);
			$returnVal = array();
			exec($cmd, $returnVal);
			$splitstring=$returnVal[0];
			$this->IM_commands[] = Array ('identify',$cmd,$returnVal[0]);
			if ($splitstring)	{
				ereg('([^\.]*)$',$imagefile,$reg);
				$splitinfo = explode(' ', $splitstring);
				while (list($key,$val) = each($splitinfo))	{
					$temp = '';
					if ($val) {$temp = explode('x', $val);}
					if (intval($temp[0]) && intval($temp[1]))	{
						$dim=$temp;
						break;
					}
				}
				if ($dim[0] && $dim[1])	{
					return Array($dim[0], $dim[1], strtolower($reg[0]), $imagefile);
				}
			}
		}
	}

	/**
	 * Executes a ImageMagick "convert" on two filenames, $input and $output using $params before them.
	 * Can be used for many things, mostly scaling and effects.
	 *
	 * @param	string		The relative (to PATH_site) image filepath, input file (read from)
	 * @param	string		The relative (to PATH_site) image filepath, output filename (written to)
	 * @param	string		ImageMagick parameters
	 * @return	string		The result of a call to PHP function "exec()"
	 */
	function imageMagickExec($input,$output,$params)	{
		if (!$this->NO_IMAGE_MAGICK)	{
			$cmd = t3lib_div::imageMagickCommand('convert', $params.' '.$this->wrapFileName($input).' '.$this->wrapFileName($output));
			$this->IM_commands[] = array($output,$cmd);

			$ret = exec($cmd);
			t3lib_div::fixPermissions($this->wrapFileName($output));	// Change the permissions of the file

			return $ret;
		}
	}

	/**
	 * Executes a ImageMagick "combine" (or composite in newer times) on four filenames - $input, $overlay and $mask as input files and $output as the output filename (written to)
	 * Can be used for many things, mostly scaling and effects.
	 *
	 * @param	string		The relative (to PATH_site) image filepath, bottom file
	 * @param	string		The relative (to PATH_site) image filepath, overlay file (top)
	 * @param	string		The relative (to PATH_site) image filepath, the mask file (grayscale)
	 * @param	string		The relative (to PATH_site) image filepath, output filename (written to)
	 * @param	[type]		$handleNegation: ...
	 * @return	void
	 */
	function combineExec($input,$overlay,$mask,$output, $handleNegation = false)	{
		if (!$this->NO_IMAGE_MAGICK)	{
			$params = '-colorspace GRAY +matte';
			if ($handleNegation)	{
				if ($this->maskNegate)	{
					$params .= ' '.$this->maskNegate;
				}
			}
			$theMask = $this->randomName().'.'.$this->gifExtension;
			$this->imageMagickExec($mask, $theMask, $params);
			$cmd = t3lib_div::imageMagickCommand('combine', '-compose over +matte '.$this->wrapFileName($input).' '.$this->wrapFileName($overlay).' '.$this->wrapFileName($theMask).' '.$this->wrapFileName($output));		// +matte = no alpha layer in output
			$this->IM_commands[] = Array ($output,$cmd);

			$ret = exec($cmd);
			t3lib_div::fixPermissions($this->wrapFileName($output));	// Change the permissions of the file

			if (is_file($theMask))	{
				@unlink($theMask);
			}

			return $ret;
		}
	}

	/**
	 * Wrapping the input filename in double-quotes
	 *
	 * @param	string		Input filename
	 * @return	string		The output wrapped in "" (if there are spaces in the filepath)
	 * @access private
	 */
	function wrapFileName($inputName)	{
		if (strstr($inputName,' '))	{
			$inputName='"'.$inputName.'"';
		}
		return $inputName;
	}























	/***********************************
	 *
	 * Various IO functions
	 *
	 ***********************************/

	/**
	 * Returns true if the input file existed
	 *
	 * @param	string		Input file to check
	 * @return	string		Returns the filename if the file existed, otherwise empty.
	 */
	function checkFile($file)	{
		if (@is_file($file))	{
			return $file;
		} else {
			return '';
		}
	}

	/**
	 * Creates subdirectory in typo3temp/ if not already found.
	 *
	 * @param	string		Name of sub directory
	 * @return	boolean		Result of t3lib_div::mkdir(), true if it went well.
	 */
	function createTempSubDir($dirName)	{

			// Checking if the this->tempPath is already prefixed with PATH_site and if not, prefix it with that constant.
		if (t3lib_div::isFirstPartOfStr($this->tempPath,PATH_site))	{
			$tmpPath = $this->tempPath;
		} else {
			$tmpPath = PATH_site.$this->tempPath;
		}

			// Making the temporary filename:
		if (!@is_dir($tmpPath.$dirName))	 {
			return t3lib_div::mkdir($tmpPath.$dirName);
		}
	}

	/**
	 * Applies an ImageMagick parameter to a GDlib image pointer resource by writing the resource to file, performing an IM operation upon it and reading back the result into the ImagePointer.
	 *
	 * @param	pointer		The image pointer (reference)
	 * @param	string		The ImageMagick parameters. Like effects, scaling etc.
	 * @return	void
	 */
	function applyImageMagickToPHPGif(&$im, $command)	{
		$tmpStr = $this->randomName();
		$theFile = $tmpStr.'.'.$this->gifExtension;
		$this->ImageWrite($im, $theFile);
		$this->imageMagickExec($theFile,$theFile,$command);
		$tmpImg = $this->imageCreateFromFile($theFile);
		if ($tmpImg)	{
			ImageDestroy($im);
			$im = $tmpImg;
			$this->w = imagesx($im);
			$this->h = imagesy($im);
		}
		if (!$this->dontUnlinkTempFiles)	{
			unlink($theFile);
		}
	}

	/**
	 * Returns an image extension for an output image based on the number of pixels of the output and the file extension of the original file.
	 * For example: If the number of pixels exceeds $this->pixelLimitGif (normally 10000) then it will be a "jpg" string in return.
	 *
	 * @param	string		The file extension, lowercase.
	 * @param	integer		The width of the output image.
	 * @param	integer		The height of the output image.
	 * @return	string		The filename, either "jpg" or "gif"/"png" (whatever $this->gifExtension is set to.)
	 */
	function gif_or_jpg($type,$w,$h)	{
		if ($type=='ai' || $w*$h < $this->pixelLimitGif)	{
			return $this->gifExtension;
		} else {
			return 'jpg';
		}
	}

	/**
	 * Writing the internal image pointer, $this->im, to file based on the extension of the input filename
	 * Used in GIFBUILDER
	 * Uses $this->setup['reduceColors'] for gif/png images and $this->setup['quality'] for jpg images to reduce size/quality if needed.
	 *
	 * @param	string		The filename to write to.
	 * @return	string		Returns input filename
	 * @see tslib_gifBuilder::gifBuild()
	 */
	function output($file)	{
		if ($file)	{
			$reg = array();
			ereg('([^\.]*)$',$file,$reg);
			$ext=strtolower($reg[0]);
			switch($ext)	{
				case 'gif':
				case 'png':
					if ($this->ImageWrite($this->im, $file))	{
							// ImageMagick operations
						if ($this->setup['reduceColors'] || (!$this->png_truecolor && $this->truecolor))	{
							$reduced = $this->IMreduceColors($file, t3lib_div::intInRange($this->setup['reduceColors'], 256, $this->truecolorColors, 256));
							if ($reduced)	{
								@copy($reduced, $file);
								@unlink($reduced);
							}
						}
						t3lib_div::gif_compress($file, 'IM');		// Compress with IM! (adds extra compression, LZW from ImageMagick)     (Workaround for the absence of lzw-compression in GD)
					}
				break;
				case 'jpg':
				case 'jpeg':
					$quality = 0;	// Use the default
					if($this->setup['quality'])	{
						$quality = t3lib_div::intInRange($this->setup['quality'],10,100);
					}
					if ($this->ImageWrite($this->im, $file, $quality));
				break;
			}
			$GLOBALS['TEMP_IMAGES_ON_PAGE'][]=$file;
		}
		return $file;
	}

	/**
	 * Destroy internal image pointer, $this->im
	 *
	 * @return	void
	 * @see tslib_gifBuilder::gifBuild()
	 */
	function destroy()	{
		ImageDestroy($this->im);
	}

	/**
	 * Returns Image Tag for input image information array.
	 *
	 * @param	array		Image information array, key 0/1 is width/height and key 3 is the src value
	 * @return	string		Image tag for the input image information array.
	 */
	function imgTag ($imgInfo) {
		return '<img src="'.$imgInfo[3].'" width="'.$imgInfo[0].'" height="'.$imgInfo[1].'" border="0" alt="" />';
	}

	/**
	 * Writes the input GDlib image pointer to file
	 *
	 * @param	pointer		The GDlib image resource pointer
	 * @param	string		The filename to write to
	 * @return	mixed		The output of either imageGif, imagePng or imageJpeg based on the filename to write
	 * @see maskImageOntoImage(), scale(), output()
	 */
	function ImageWrite($destImg, $theImage)	{
		imageinterlace ($destImg,0);
 		$ext = strtolower(substr($theImage, strrpos($theImage, '.')+1));
 		switch ($ext)	{
 			case 'jpg':
 			case 'jpeg':
 				if (function_exists('imageJpeg'))	{
 					return imageJpeg($destImg, $theImage, $this->jpegQuality);
 				}
 			break;
 			case 'gif':
 				if (function_exists('imageGif'))	{
					if ($this->truecolor)	{
						imagetruecolortopalette($destImg, true, 256);
					}
 					return imageGif($destImg, $theImage);
 				}
 			break;
 			case 'png':
 				if (function_exists('imagePng'))	{
 					return ImagePng($destImg, $theImage);
 				}
 			break;
 		}
 		return false;		// Extension invalid or write-function does not exist
 	}



 	/**
 * Writes the input GDlib image pointer to file. Now just a wrapper to ImageWrite.
 *
 * @param	pointer		The GDlib image resource pointer
 * @param	string		The filename to write to
 * @return	mixed		The output of either imageGif, imagePng or imageJpeg based on the filename to write
 * @see imageWrite()
 * @deprecated
 */
 	function imageGif($destImg, $theImage)	{
 		return $this->imageWrite($destImg, $theImage);
	}

	/**
	 * This function has been renamed and only exists for providing backwards compatibility.
	 * Please use $this->imageCreateFromFile() instead.
	 *
	 * @param	string		Image filename
	 * @return	pointer		Image Resource pointer
	 * @deprecated
	 */
	function imageCreateFromGif($sourceImg)	{
		return $this->imageCreateFromFile($sourceImg);
	}

	/**
	 * Creates a new GDlib image resource based on the input image filename.
	 * If it fails creating a image from the input file a blank gray image with the dimensions of the input image will be created instead.
	 *
	 * @param	string		Image filename
	 * @return	pointer		Image Resource pointer
	 */
	function imageCreateFromFile($sourceImg)	{
		$imgInf = pathinfo($sourceImg);
		$ext = strtolower($imgInf['extension']);

		switch ($ext)	{
			case 'gif':
				if (function_exists('imagecreatefromgif'))	{
					return imageCreateFromGif($sourceImg);
				}
			break;
			case 'png':
				if (function_exists('imagecreatefrompng'))	{
					return imageCreateFromPng($sourceImg);
				}
			break;
			case 'jpg':
			case 'jpeg':
				if (function_exists('imagecreatefromjpeg'))	{
					return imageCreateFromJpeg($sourceImg);
				}
			break;
		}

		// If non of the above:
		$i = @getimagesize($sourceImg);
		$im = $this->imagecreate($i[0],$i[1]);
		$Bcolor = ImageColorAllocate($im, 128,128,128);
		ImageFilledRectangle($im, 0, 0, $i[0], $i[1], $Bcolor);
		return $im;
	}


	/**
	 * Creates a new GD image resource. Wrapper for imagecreate(truecolor) depended if GD2 is used.
	 *
	 * @param	integer		Width of image
	 * @param	integer		Height of image
	 * @return	pointer		Image Resource pointer
	 */
	function imagecreate($w, $h)	{
		if($this->truecolor && function_exists('imagecreatetruecolor'))	{
			return imagecreatetruecolor($w, $h);
		} else	{
			return imagecreate($w, $h);
		}

	}

	/**
	 * Returns the HEX color value for an RGB color array
	 *
	 * @param	array		RGB color array
	 * @return	string		HEX color value
	 */
	function hexColor($col)	{
		$r = dechex($col[0]);
		if (strlen($r)<2)	{ $r = '0'.$r; }
		$g = dechex($col[1]);
		if (strlen($g)<2)	{ $g = '0'.$g; }
		$b = dechex($col[2]);
		if (strlen($b)<2)	{ $b = '0'.$b; }
		return '#'.$r.$g.$b;
	}

	/**
	 * Unifies all colors given in the colArr color array to the first color in the array.
	 *
	 * @param	pointer		Image resource
	 * @param	array		Array containing RGB color arrays
	 * @param	[type]		$closest: ...
	 * @return	integer		The index of the unified color
	 */
	function unifyColors(&$img, $colArr, $closest = false)	{
		$retCol = -1;
		if (is_array($colArr) && count($colArr) && function_exists('imagepng') && function_exists('imagecreatefrompng'))	{
			$firstCol = array_shift($colArr);
			$firstColArr = $this->convertColor($firstCol);
			if (count($colArr)>1)	{
				$origName = $preName = $this->randomName().'.png';
				$postName = $this->randomName().'.png';
				$this->imageWrite($img, $preName);
				$firstCol = $this->hexColor($firstColArr);
				foreach ($colArr as $transparentColor)	{
					$transparentColor = $this->convertColor($transparentColor);
					$transparentColor = $this->hexColor($transparentColor);
					$cmd = '-fill "'.$firstCol.'" -opaque "'.$transparentColor.'"';
					$this->imageMagickExec($preName, $postName, $cmd);
					$preName = $postName;
				}
				$this->imageMagickExec($postName, $origName, '');
				if (@is_file($origName))	{
					$tmpImg = $this->imageCreateFromFile($origName);
				}
			} else	{
				$tmpImg = $img;
			}
			if ($tmpImg)	{
				$img = $tmpImg;
				if ($closest)	{
					$retCol = ImageColorClosest ($img, $firstColArr[0], $firstColArr[1], $firstColArr[2]);
				} else	{
					$retCol = ImageColorExact ($img, $firstColArr[0], $firstColArr[1], $firstColArr[2]);
				}
			}
				// unlink files from process
			if (!$this->dontUnlinkTempFiles)	{
				if ($origName)	{
					@unlink($origName);
				}
				if ($postName)	{
					@unlink($postName);
				}
			}
		}
		return $retCol;
	}


}

if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_stdgraphic.php'])	{
	include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_stdgraphic.php']);
}
?>