Fixed bug #12017: Wrong Inclusion in tceforms and tceforms_fe
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_stdgraphic.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 1999-2009 Kasper Skaarhoj (kasperYYYY@typo3.com)
6 * All rights reserved
7 *
8 * This script is part of the TYPO3 project. The TYPO3 project is
9 * free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * The GNU General Public License can be found at
15 * http://www.gnu.org/copyleft/gpl.html.
16 * A copy is found in the textfile GPL.txt and important notices to the license
17 * from the author is found in LICENSE.txt distributed with these scripts.
18 *
19 *
20 * This script is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
24 *
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
27 /**
28 * Standard graphical functions
29 *
30 * $Id$
31 * Revised for TYPO3 3.6 July/2003 by Kasper Skaarhoj
32 *
33 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
34 */
35 /**
36 * [CLASS/FUNCTION INDEX of SCRIPT]
37 *
38 *
39 *
40 * 155: class t3lib_stdGraphic
41 * 236: function init()
42 *
43 * SECTION: Layering images / "IMAGE" GIFBUILDER object
44 * 366: function maskImageOntoImage(&$im,$conf,$workArea)
45 * 436: function copyImageOntoImage(&$im,$conf,$workArea)
46 * 458: function copyGifOntoGif(&$im,$cpImg,$conf,$workArea)
47 * 537: function imagecopyresized(&$im, $cpImg, $Xstart, $Ystart, $cpImgCutX, $cpImgCutY, $w, $h, $w, $h)
48 *
49 * SECTION: Text / "TEXT" GIFBUILDER object
50 * 587: function makeText(&$im,$conf,$workArea)
51 * 707: function txtPosition($conf,$workArea,$BB)
52 * 761: function calcBBox($conf)
53 * 820: function addToMap($cords,$conf)
54 * 843: function calcTextCordsForMap($cords,$offset, $conf)
55 * 878: function SpacedImageTTFText(&$im, $fontSize, $angle, $x, $y, $Fcolor, $fontFile, $text, $spacing, $wordSpacing, $splitRenderingConf, $sF=1)
56 * 915: function fontResize($conf)
57 * 958: function ImageTTFBBoxWrapper($fontSize, $angle, $fontFile, $string, $splitRendering, $sF=1)
58 * 1005: function ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $color, $fontFile, $string, $splitRendering,$sF=1)
59 * 1058: function splitString($string,$splitRendering,$fontSize,$fontFile)
60 * 1208: function calcWordSpacing($conf, $scaleFactor=1)
61 * 1227: function getTextScalFactor($conf)
62 *
63 * SECTION: Other GIFBUILDER objects related to TEXT
64 * 1262: function makeOutline(&$im,$conf,$workArea,$txtConf)
65 * 1291: function circleOffset($distance, $iterations)
66 * 1315: function makeEmboss(&$im,$conf,$workArea,$txtConf)
67 * 1337: function makeShadow(&$im,$conf,$workArea,$txtConf)
68 *
69 * SECTION: Other GIFBUILDER objects
70 * 1469: function makeBox(&$im,$conf,$workArea)
71 * 1491: function makeEffect(&$im, $conf)
72 * 1506: function IMparams($setup)
73 * 1589: function adjust(&$im, $conf)
74 * 1621: function crop(&$im,$conf)
75 * 1652: function scale(&$im,$conf)
76 * 1684: function setWorkArea($workArea)
77 *
78 * SECTION: Adjustment functions
79 * 1725: function autolevels(&$im)
80 * 1756: function outputLevels(&$im,$low,$high,$swap='')
81 * 1788: function inputLevels(&$im,$low,$high,$swap='')
82 * 1819: function reduceColors(&$im,$limit, $cols)
83 * 1832: function IMreduceColors($file, $cols)
84 *
85 * SECTION: GIFBUILDER Helper functions
86 * 1875: function prependAbsolutePath($fontFile)
87 * 1889: function v5_sharpen($factor)
88 * 1908: function v5_blur($factor)
89 * 1925: function randomName()
90 * 1938: function applyOffset($cords,$OFFSET)
91 * 1951: function convertColor($string)
92 * 2001: function recodeString($string)
93 * 2023: function singleChars($theText,$returnUnicodeNumber=FALSE)
94 * 2046: function objPosition($conf,$workArea,$BB)
95 *
96 * SECTION: Scaling, Dimensions of images
97 * 2125: function imageMagickConvert($imagefile,$newExt='',$w='',$h='',$params='',$frame='',$options='',$mustCreate=0)
98 * 2238: function getImageDimensions($imageFile)
99 * 2266: function cacheImageDimensions($identifyResult)
100 * 2298: function getCachedImageDimensions($imageFile)
101 * 2332: function getImageScale($info,$w,$h,$options)
102 * 2438: function file_exists_typo3temp_file($output,$orig='')
103 *
104 * SECTION: ImageMagick API functions
105 * 2499: function imageMagickIdentify($imagefile)
106 * 2534: function imageMagickExec($input,$output,$params)
107 * 2557: function combineExec($input,$overlay,$mask,$output, $handleNegation = false)
108 * 2588: function wrapFileName($inputName)
109 *
110 * SECTION: Various IO functions
111 * 2629: function checkFile($file)
112 * 2643: function createTempSubDir($dirName)
113 * 2665: function applyImageMagickToPHPGif(&$im, $command)
114 * 2691: function gif_or_jpg($type,$w,$h)
115 * 2708: function output($file)
116 * 2748: function destroy()
117 * 2758: function imgTag ($imgInfo)
118 * 2770: function ImageWrite($destImg, $theImage)
119 * 2808: function imageGif($destImg, $theImage)
120 * 2820: function imageCreateFromGif($sourceImg)
121 * 2831: function imageCreateFromFile($sourceImg)
122 * 2870: function imagecreate($w, $h)
123 * 2885: function hexColor($col)
124 * 2903: function unifyColors(&$img, $colArr, $closest = false)
125 *
126 * TOTAL FUNCTIONS: 66
127 * (This index is automatically created/updated by the extension "extdeveval")
128 *
129 */
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146 /**
147 * Class contains a bunch of cool functions for manipulating graphics with GDlib/Freetype and ImageMagick
148 * VERY OFTEN used with gifbuilder that extends this class and provides a TypoScript API to using these functions
149 *
150 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
151 * @package TYPO3
152 * @subpackage t3lib
153 * @see tslib_gifBuilder
154 */
155 class t3lib_stdGraphic {
156
157 // Internal configuration, set in init()
158 var $combineScript = 'combine'; // The ImageMagick filename used for combining two images. This name changed during the versions.
159 var $noFramePrepended=0; // If set, there is no frame pointer prepended to the filenames.
160 var $GD2=0; // Set, if the GDlib used is version 2.
161 var $imagecopyresized_fix=0; // If set, imagecopyresized will not be called directly. For GD2 (some PHP installs?)
162 var $gifExtension = 'gif'; // This should be changed to 'png' if you want this class to read/make PNG-files instead!
163 var $gdlibExtensions = ''; // File formats supported by gdlib. This variable get's filled in "init" method
164 var $truecolor = true; // Internal variable which get's used to determine wheter GDlib should use function truecolor pendants
165 var $png_truecolor = false; // Set to true if generated png's should be truecolor by default
166 var $truecolorColors = 0xffffff; // 16777216 Colors is the maximum value for PNG, JPEG truecolor images (24-bit, 8-bit / Channel)
167 var $TTFLocaleConv = ''; // Used to recode input to TTF-functions for other charsets.
168 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.
169 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!
170 var $webImageExt = 'gif,jpg,jpeg,png'; // Commalist of web image extensions (can be shown by a webbrowser)
171 var $maskNegate = ''; // Will be ' -negate' if ImageMagick ver 5.2+. See init();
172 var $NO_IM_EFFECTS = '';
173 var $cmds = Array (
174 'jpg' => '',
175 'jpeg' => '',
176 'gif' => '-colors 64',
177 'png' => '-colors 64'
178 );
179 var $NO_IMAGE_MAGICK = '';
180 var $V5_EFFECTS = 0;
181 var $im_version_4 = 0;
182 var $mayScaleUp = 1;
183
184 // Variables for testing, alternative usage etc.
185 var $filenamePrefix=''; // Filename prefix for images scaled in imageMagickConvert()
186 var $imageMagickConvert_forceFileNameBody=''; // Forcing the output filename of imageMagickConvert() to this value. However after calling imageMagickConvert() it will be set blank again.
187 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.
188 var $dontCompress=0; // Prevents imageMagickConvert() from compressing the gif-files with t3lib_div::gif_compress()
189 var $dontUnlinkTempFiles=0; // For debugging ONLY!
190 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...
191
192 // Internal:
193 var $IM_commands = Array(); // All ImageMagick commands executed is stored in this array for tracking. Used by the Install Tools Image section
194 var $workArea = Array();
195
196 // Constants:
197 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.
198 var $absPrefix = ''; // Prefix for relative paths. Used in "show_item.php" script. Is prefixed the output file name IN imageMagickConvert()
199 var $scalecmd = '-geometry'; // ImageMagick scaling command; "-geometry" eller "-sample". Used in makeText() and imageMagickConvert()
200 var $im5fx_blurSteps='1x2,2x2,3x2,4x3,5x3,5x4,6x4,7x5,8x5,9x5'; // Used by v5_blur() to simulate 10 continuous steps of blurring
201 var $im5fx_sharpenSteps='1x2,2x2,3x2,2x3,3x3,4x3,3x4,4x4,4x5,5x5'; // Used by v5_sharpen() to simulate 10 continuous steps of sharpening.
202 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
203 var $colMap = Array ( // Array mapping HTML color names to RGB values.
204 'aqua' => Array(0,255,255),
205 'black' => Array(0,0,0),
206 'blue' => Array(0,0,255),
207 'fuchsia' => Array(255,0,255),
208 'gray' => Array(128,128,128),
209 'green' => Array(0,128,0),
210 'lime' => Array(0,255,0),
211 'maroon' => Array(128,0,0),
212 'navy' => Array(0,0,128),
213 'olive' => Array(128,128,0),
214 'purple' => Array(128,0,128),
215 'red' => Array(255,0,0),
216 'silver' => Array(192,192,192),
217 'teal' => Array(0,128,128),
218 'yellow' => Array(255,255,0),
219 'white' => Array(255,255,255)
220 );
221
222 /**
223 * Charset conversion object:
224 *
225 * @var t3lib_cs
226 */
227 var $csConvObj;
228 var $nativeCharset=''; // Is set to the native character set of the input strings.
229
230
231
232
233
234 /**
235 * Init function. Must always call this when using the class.
236 * This function will read the configuration information from $GLOBALS['TYPO3_CONF_VARS']['GFX'] can set some values in internal variables.
237 *
238 * @return void
239 */
240 function init() {
241 $gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX'];
242
243 if (function_exists('imagecreatefromjpeg')&&function_exists('imagejpeg')) {
244 $this->gdlibExtensions .= ',jpg,jpeg';
245 }
246 if (function_exists('imagecreatefrompng')&&function_exists('imagepng')) {
247 $this->gdlibExtensions .= ',png';
248 }
249 if (function_exists('imagecreatefromgif')&&function_exists('imagegif')) {
250 $this->gdlibExtensions .= ',gif';
251 }
252 if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['png_truecolor']) {
253 $this->png_truecolor = true;
254 }
255 if (!$gfxConf['gdlib_2'] || !function_exists('imagecreatetruecolor')) {
256 $this->truecolor = false;
257 }
258 if (!$gfxConf['im_version_5']) {
259 $this->im_version_4 = true;
260 }
261
262 // When GIFBUILDER gets used in truecolor mode (GD2 required)
263 if ($this->truecolor) {
264 if ($this->png_truecolor) {
265 $this->cmds['png'] = ''; // No colors parameter if we generate truecolor images.
266 }
267 $this->cmds['gif'] = ''; // No colors parameter if we generate truecolor images.
268 }
269
270 // Setting default JPG parameters:
271 $this->jpegQuality = t3lib_div::intInRange($gfxConf['jpg_quality'], 10, 100, 75);
272 $this->cmds['jpg'] = $this->cmds['jpeg'] = '-colorspace RGB -sharpen 50 -quality '.$this->jpegQuality;
273
274 if ($gfxConf['im_combine_filename']) $this->combineScript=$gfxConf['im_combine_filename'];
275 if ($gfxConf['im_noFramePrepended']) $this->noFramePrepended=1;
276
277 if ($gfxConf['gdlib_2']) {
278 $this->GD2 = 1;
279 $this->imagecopyresized_fix = $gfxConf['gdlib_2']==='no_imagecopyresized_fix' ? 0 : 1;
280 }
281 if ($gfxConf['gdlib_png']) {
282 $this->gifExtension='png';
283 }
284 if ($gfxConf['TTFLocaleConv']) {
285 $this->TTFLocaleConv = $gfxConf['TTFLocaleConv'];
286 }
287 if ($gfxConf['enable_typo3temp_db_tracking']) {
288 $this->enable_typo3temp_db_tracking = $gfxConf['enable_typo3temp_db_tracking'];
289 }
290
291 $this->imageFileExt = $gfxConf['imagefile_ext'];
292
293 // This should be set if ImageMagick ver. 5+ is used.
294 if ($gfxConf['im_negate_mask']) {
295 // Boolean. Indicates if the mask images should be inverted first.
296 // This depends of the ImageMagick version. Below ver. 5.1 this should be false.
297 // Above ImageMagick version 5.2+ it should be true.
298 // Just set the flag if the masks works opposite the intension!
299 $this->maskNegate = ' -negate';
300 }
301 if ($gfxConf['im_no_effects']) {
302 // Boolean. This is necessary if using ImageMagick 5+.
303 // Approved version for using effects is version 4.2.9.
304 // Effects in Imagemagick 5+ tends to render very slowly!!
305 // - therefore must be disabled in order not to perform sharpen, blurring and such.
306 $this->NO_IM_EFFECTS = 1;
307
308 $this->cmds['jpg'] = $this->cmds['jpeg'] = '-colorspace RGB -quality '.$this->jpegQuality;
309 }
310 // ... but if 'im_v5effects' is set, don't care about 'im_no_effects'
311 if ($gfxConf['im_v5effects']) {
312 $this->NO_IM_EFFECTS = 0;
313 $this->V5_EFFECTS = 1;
314
315 if ($gfxConf['im_v5effects']>0) {
316 $this->cmds['jpg'] = $this->cmds['jpeg'] = '-colorspace RGB -quality '.intval($gfxConf['jpg_quality']).$this->v5_sharpen(10);
317 }
318 }
319
320 if (!$gfxConf['im']) {
321 $this->NO_IMAGE_MAGICK = 1;
322 }
323 // Secures that images are not scaled up.
324 if ($gfxConf['im_noScaleUp']) {
325 $this->mayScaleUp=0;
326 }
327
328 if (TYPO3_MODE=='FE') {
329 $this->csConvObj = $GLOBALS['TSFE']->csConvObj;
330 } elseif(is_object($GLOBALS['LANG'])) { // BE assumed:
331 $this->csConvObj = $GLOBALS['LANG']->csConvObj;
332 } else { // The object may not exist yet, so we need to create it now. Happens in the Install Tool for example.
333 $this->csConvObj = t3lib_div::makeInstance('t3lib_cs');
334 }
335 $this->nativeCharset = $GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'];
336 }
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353 /*************************************************
354 *
355 * Layering images / "IMAGE" GIFBUILDER object
356 *
357 *************************************************/
358
359 /**
360 * Implements the "IMAGE" GIFBUILDER object, when the "mask" property is true.
361 * 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
362 * The operation involves ImageMagick for combining.
363 *
364 * @param pointer GDlib image pointer
365 * @param array TypoScript array with configuration for the GIFBUILDER object.
366 * @param array The current working area coordinates.
367 * @return void
368 * @see tslib_gifBuilder::make()
369 */
370 function maskImageOntoImage(&$im,$conf,$workArea) {
371 if ($conf['file'] && $conf['mask']) {
372 $imgInf = pathinfo($conf['file']);
373 $imgExt = strtolower($imgInf['extension']);
374 if (!t3lib_div::inList($this->gdlibExtensions, $imgExt)) {
375 $BBimage = $this->imageMagickConvert($conf['file'],$this->gifExtension,'','','','','');
376 } else {
377 $BBimage = $this->getImageDimensions($conf['file']);
378 }
379 $maskInf = pathinfo($conf['mask']);
380 $maskExt = strtolower($maskInf['extension']);
381 if (!t3lib_div::inList($this->gdlibExtensions, $maskExt)) {
382 $BBmask = $this->imageMagickConvert($conf['mask'],$this->gifExtension,'','','','','');
383 } else {
384 $BBmask = $this->getImageDimensions($conf['mask']);
385 }
386 if ($BBimage && $BBmask) {
387 $w = imagesx($im);
388 $h = imagesy($im);
389 $tmpStr = $this->randomName();
390 $theImage = $tmpStr.'_img.'.$this->gifExtension;
391 $theDest = $tmpStr.'_dest.'.$this->gifExtension;
392 $theMask = $tmpStr.'_mask.'.$this->gifExtension;
393 // prepare overlay image
394 $cpImg = $this->imageCreateFromFile($BBimage[3]);
395 $destImg = $this->imagecreate($w,$h);
396 $Bcolor = ImageColorAllocate($destImg, 0,0,0);
397 ImageFilledRectangle($destImg, 0, 0, $w, $h, $Bcolor);
398 $this->copyGifOntoGif($destImg,$cpImg,$conf,$workArea);
399 $this->ImageWrite($destImg, $theImage);
400 imageDestroy($cpImg);
401 imageDestroy($destImg);
402 // prepare mask image
403 $cpImg = $this->imageCreateFromFile($BBmask[3]);
404 $destImg = $this->imagecreate($w,$h);
405 $Bcolor = ImageColorAllocate($destImg, 0, 0, 0);
406 ImageFilledRectangle($destImg, 0, 0, $w, $h, $Bcolor);
407 $this->copyGifOntoGif($destImg,$cpImg,$conf,$workArea);
408 $this->ImageWrite($destImg, $theMask);
409 imageDestroy($cpImg);
410 imageDestroy($destImg);
411 // mask the images
412 $this->ImageWrite($im, $theDest);
413
414 $this->combineExec($theDest,$theImage,$theMask,$theDest, true); // Let combineExec handle maskNegation
415
416 $backIm = $this->imageCreateFromFile($theDest); // The main image is loaded again...
417 if ($backIm) { // ... and if nothing went wrong we load it onto the old one.
418 ImageColorTransparent($backIm,-1);
419 $im = $backIm;
420 }
421 // unlink files from process
422 if (!$this->dontUnlinkTempFiles) {
423 unlink($theDest);
424 unlink($theImage);
425 unlink($theMask);
426 }
427 }
428 }
429 }
430
431 /**
432 * Implements the "IMAGE" GIFBUILDER object, when the "mask" property is false (using only $conf['file'])
433 *
434 * @param pointer GDlib image pointer
435 * @param array TypoScript array with configuration for the GIFBUILDER object.
436 * @param array The current working area coordinates.
437 * @return void
438 * @see tslib_gifBuilder::make(), maskImageOntoImage()
439 */
440 function copyImageOntoImage(&$im,$conf,$workArea) {
441 if ($conf['file']) {
442 if (!t3lib_div::inList($this->gdlibExtensions, $conf['BBOX'][2])) {
443 $conf['BBOX']=$this->imageMagickConvert($conf['BBOX'][3],$this->gifExtension,'','','','','');
444 $conf['file']=$conf['BBOX'][3];
445 }
446 $cpImg = $this->imageCreateFromFile($conf['file']);
447 $this->copyGifOntoGif($im,$cpImg,$conf,$workArea);
448 imageDestroy($cpImg);
449 }
450 }
451
452 /**
453 * Copies two GDlib image pointers onto each other, using TypoScript configuration from $conf and the input $workArea definition.
454 *
455 * @param pointer GDlib image pointer, destination (bottom image)
456 * @param pointer GDlib image pointer, source (top image)
457 * @param array TypoScript array with the properties for the IMAGE GIFBUILDER object. Only used for the "tile" property value.
458 * @param array Work area
459 * @return void Works on the $im image pointer
460 * @access private
461 */
462 function copyGifOntoGif(&$im,$cpImg,$conf,$workArea) {
463 $cpW = imagesx($cpImg);
464 $cpH = imagesy($cpImg);
465 $tile = t3lib_div::intExplode(',',$conf['tile']);
466 $tile[0] = t3lib_div::intInRange($tile[0],1,20);
467 $tile[1] = t3lib_div::intInRange($tile[1],1,20);
468 $cpOff = $this->objPosition($conf,$workArea,Array($cpW*$tile[0],$cpH*$tile[1]));
469
470 for ($xt=0;$xt<$tile[0];$xt++) {
471 $Xstart=$cpOff[0]+$cpW*$xt;
472 if ($Xstart+$cpW > $workArea[0]) { // if this image is inside of the workArea, then go on
473 // X:
474 if ($Xstart < $workArea[0]) {
475 $cpImgCutX = $workArea[0]-$Xstart;
476 $Xstart = $workArea[0];
477 } else {
478 $cpImgCutX = 0;
479 }
480 $w = $cpW-$cpImgCutX;
481 if ($Xstart > $workArea[0]+$workArea[2]-$w) {
482 $w = $workArea[0]+$workArea[2]-$Xstart;
483 }
484 if ($Xstart < $workArea[0]+$workArea[2]) { // if this image is inside of the workArea, then go on
485 // Y:
486 for ($yt=0;$yt<$tile[1];$yt++) {
487 $Ystart=$cpOff[1]+$cpH*$yt;
488 if ($Ystart+$cpH > $workArea[1]) { // if this image is inside of the workArea, then go on
489 if ($Ystart < $workArea[1]) {
490 $cpImgCutY = $workArea[1]-$Ystart;
491 $Ystart = $workArea[1];
492 } else {
493 $cpImgCutY = 0;
494 }
495 $h = $cpH-$cpImgCutY;
496 if ($Ystart > $workArea[1]+$workArea[3]-$h) {
497 $h = $workArea[1]+$workArea[3]-$Ystart;
498 }
499 if ($Ystart < $workArea[1]+$workArea[3]) { // if this image is inside of the workArea, then go on
500 $this->imagecopyresized($im, $cpImg, $Xstart, $Ystart, $cpImgCutX, $cpImgCutY, $w, $h, $w, $h);
501 }
502 }
503 } // Y:
504 }
505 }
506 }
507 }
508
509 /**
510 * Alternative function for using the similar PHP function imagecopyresized(). Used for GD2 only.
511 *
512 * OK, the reason for this stupid fix is the following story:
513 * GD1.x was capable of copying two images together and combining their palettes! GD2 is apparently not.
514 * With GD2 only the palette of the dest-image is used which mostly results in totally black images when trying to
515 * copy a color-ful image onto the destination.
516 * The GD2-fix is to
517 * 1) Create a blank TRUE-COLOR image
518 * 2) Copy the destination image onto that one
519 * 3) Then do the actual operation; Copying the source (top image) onto that
520 * 4) ... and return the result pointer.
521 * 5) Reduce colors (if we do not, the result may become strange!)
522 * It works, but the resulting images is now a true-color PNG which may be very large.
523 * So, why not use 'imagetruecolortopalette ($im, TRUE, 256)' - well because it does NOT WORK! So simple is that.
524 *
525 * For parameters, see PHP function "imagecopyresized()"
526 *
527 * @param pointer see PHP function "imagecopyresized()"
528 * @param pointer see PHP function "imagecopyresized()"
529 * @param integer see PHP function "imagecopyresized()"
530 * @param integer see PHP function "imagecopyresized()"
531 * @param integer see PHP function "imagecopyresized()"
532 * @param integer see PHP function "imagecopyresized()"
533 * @param integer see PHP function "imagecopyresized()"
534 * @param integer see PHP function "imagecopyresized()"
535 * @param integer see PHP function "imagecopyresized()"
536 * @param integer see PHP function "imagecopyresized()"
537 * @return void
538 * @access private
539 * @see t3lib_iconWorks::imagecopyresized()
540 */
541 function imagecopyresized(&$im, $cpImg, $Xstart, $Ystart, $cpImgCutX, $cpImgCutY, $w, $h, $w, $h) {
542 if ($this->imagecopyresized_fix) {
543 $im_base = $this->imagecreate(imagesx($im), imagesy($im)); // Make true color image
544 imagecopyresized($im_base, $im, 0,0,0,0, imagesx($im),imagesy($im),imagesx($im),imagesy($im)); // Copy the source image onto that
545 imagecopyresized($im_base, $cpImg, $Xstart, $Ystart, $cpImgCutX, $cpImgCutY, $w, $h, $w, $h); // Then copy the $cpImg onto that (the actual operation!)
546 $im = $im_base; // Set pointer
547 if (!$this->truecolor) {
548 $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!
549 }
550 } else {
551 imagecopyresized($im, $cpImg, $Xstart, $Ystart, $cpImgCutX, $cpImgCutY, $w, $h, $w, $h);
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 * Text / "TEXT" GIFBUILDER object
579 *
580 ********************************/
581
582 /**
583 * Implements the "TEXT" GIFBUILDER object
584 *
585 * @param pointer GDlib image pointer
586 * @param array TypoScript array with configuration for the GIFBUILDER object.
587 * @param array The current working area coordinates.
588 * @return void
589 * @see tslib_gifBuilder::make()
590 */
591 function makeText(&$im,$conf,$workArea) {
592 // Spacing
593 list($spacing,$wordSpacing) = $this->calcWordSpacing($conf);
594 // Position
595 $txtPos = $this->txtPosition($conf,$workArea,$conf['BBOX']);
596 $theText = $this->recodeString($conf['text']);
597
598 if ($conf['imgMap'] && is_array($conf['imgMap.'])) {
599 $this->addToMap($this->calcTextCordsForMap($conf['BBOX'][2],$txtPos, $conf['imgMap.']), $conf['imgMap.']);
600 }
601 if (!$conf['hideButCreateMap']) {
602 // Font Color:
603 $cols=$this->convertColor($conf['fontColor']);
604 // NiceText is calculated
605 if (!$conf['niceText']) {
606 // Font Color is reserved:
607 if (!$this->truecolor) {
608 $reduce = t3lib_div::intInRange($this->setup['reduceColors'], 256, $this->truecolorColors, 256);
609 $this->reduceColors($im, $reduce-49, $reduce-50); // If "reduce-49" colors (or more) are used reduce them to "reduce-50"
610 }
611 $Fcolor = ImageColorAllocate($im, $cols[0],$cols[1],$cols[2]);
612 // antiAliasing is setup:
613 $Fcolor = ($conf['antiAlias']) ? $Fcolor : -$Fcolor;
614
615 for ($a=0; $a<$conf['iterations']; $a++) {
616 if ($spacing || $wordSpacing) { // If any kind of spacing applys, we use this function:
617 $this->SpacedImageTTFText($im, $conf['fontSize'], $conf['angle'], $txtPos[0], $txtPos[1], $Fcolor, t3lib_stdGraphic::prependAbsolutePath($conf['fontFile']), $theText, $spacing, $wordSpacing, $conf['splitRendering.']);
618 } else {
619 $this->renderTTFText($im, $conf['fontSize'], $conf['angle'], $txtPos[0], $txtPos[1], $Fcolor, $conf['fontFile'], $theText, $conf['splitRendering.'], $conf);
620 }
621 }
622 } else { // NICETEXT::
623 // options anti_aliased and iterations is NOT available when doing this!!
624 $w = imagesx($im);
625 $h = imagesy($im);
626 $tmpStr = $this->randomName();
627
628 $fileMenu = $tmpStr.'_menuNT.'.$this->gifExtension;
629 $fileColor = $tmpStr.'_colorNT.'.$this->gifExtension;
630 $fileMask = $tmpStr.'_maskNT.'.$this->gifExtension;
631 // Scalefactor
632 $sF = t3lib_div::intInRange($conf['niceText.']['scaleFactor'],2,5);
633 $newW = ceil($sF*imagesx($im));
634 $newH = ceil($sF*imagesy($im));
635
636 // Make mask
637 $maskImg = $this->imagecreate($newW, $newH);
638 $Bcolor = ImageColorAllocate($maskImg, 255,255,255);
639 ImageFilledRectangle($maskImg, 0, 0, $newW, $newH, $Bcolor);
640 $Fcolor = ImageColorAllocate($maskImg, 0,0,0);
641 if ($spacing || $wordSpacing) { // If any kind of spacing applys, we use this function:
642 $this->SpacedImageTTFText($maskImg, $conf['fontSize'], $conf['angle'], $txtPos[0], $txtPos[1], $Fcolor, t3lib_stdGraphic::prependAbsolutePath($conf['fontFile']), $theText, $spacing, $wordSpacing, $conf['splitRendering.'],$sF);
643 } else {
644 $this->renderTTFText($maskImg, $conf['fontSize'], $conf['angle'], $txtPos[0], $txtPos[1], $Fcolor, $conf['fontFile'], $theText, $conf['splitRendering.'], $conf, $sF);
645 }
646 $this->ImageWrite($maskImg, $fileMask);
647 ImageDestroy($maskImg);
648
649 // Downscales the mask
650 if ($this->NO_IM_EFFECTS) {
651 if ($this->maskNegate) {
652 $command = trim($this->scalecmd.' '.$w.'x'.$h.'!'); // Negate 2 times makes no negate...
653 } else {
654 $command = trim($this->scalecmd.' '.$w.'x'.$h.'! -negate');
655 }
656 } else {
657 if ($this->maskNegate) {
658 $command = trim($conf['niceText.']['before'].' '.$this->scalecmd.' '.$w.'x'.$h.'! '.$conf['niceText.']['after']);
659 } else {
660 $command = trim($conf['niceText.']['before'].' '.$this->scalecmd.' '.$w.'x'.$h.'! '.$conf['niceText.']['after'].' -negate');
661 }
662 if ($conf['niceText.']['sharpen']) {
663 if ($this->V5_EFFECTS) {
664 $command.=$this->v5_sharpen($conf['niceText.']['sharpen']);
665 } else {
666 $command.=' -sharpen '.t3lib_div::intInRange($conf['niceText.']['sharpen'],1,99);
667 }
668 }
669 }
670
671 $this->imageMagickExec($fileMask,$fileMask,$command);
672
673 // Make the color-file
674 $colorImg = $this->imagecreate($w,$h);
675 $Ccolor = ImageColorAllocate($colorImg, $cols[0],$cols[1],$cols[2]);
676 ImageFilledRectangle($colorImg, 0, 0, $w, $h, $Ccolor);
677 $this->ImageWrite($colorImg, $fileColor);
678 ImageDestroy($colorImg);
679
680 // The mask is applied
681 $this->ImageWrite($im, $fileMenu); // The main pictures is saved temporarily
682
683 $this->combineExec($fileMenu,$fileColor,$fileMask, $fileMenu);
684
685 $backIm = $this->imageCreateFromFile($fileMenu); // The main image is loaded again...
686 if ($backIm) { // ... and if nothing went wrong we load it onto the old one.
687 ImageColorTransparent($backIm,-1);
688 $im = $backIm;
689 }
690
691 // Deleting temporary files;
692 if (!$this->dontUnlinkTempFiles) {
693 unlink($fileMenu);
694 unlink($fileColor);
695 unlink($fileMask);
696 }
697 }
698 }
699 }
700
701 /**
702 * Calculates text position for printing the text onto the image based on configuration like alignment and workarea.
703 *
704 * @param array TypoScript array for the TEXT GIFBUILDER object
705 * @param array Workarea definition
706 * @param array Bounding box information, was set in tslib_gifBuilder::start()
707 * @return array [0]=x, [1]=y, [2]=w, [3]=h
708 * @access private
709 * @see makeText()
710 */
711 function txtPosition($conf,$workArea,$BB) {
712 $bbox = $BB[2];
713 $angle=intval($conf['angle'])/180*pi();
714 $conf['angle']=0;
715 $straightBB = $this->calcBBox($conf);
716
717 // offset, align, valign, workarea
718 $result=Array(); // [0]=x, [1]=y, [2]=w, [3]=h
719 $result[2] = $BB[0];
720 $result[3] = $BB[1];
721 $w=$workArea[2];
722 $h=$workArea[3];
723
724 switch($conf['align']) {
725 case 'right':
726 case 'center':
727 $factor=abs(cos($angle));
728 $sign=(cos($angle)<0)?-1:1;
729 $len1 = $sign*$factor*$straightBB[0];
730 $len2= $sign*$BB[0];
731 $result[0] = $w-ceil($len2*$factor+(1-$factor)*$len1);
732
733 $factor=abs(sin($angle));
734 $sign=(sin($angle)<0)?-1:1;
735 $len1= $sign*$factor*$straightBB[0];
736 $len2= $sign*$BB[1];
737 $result[1]=ceil($len2*$factor+(1-$factor)*$len1);
738 break;
739 }
740 switch($conf['align']) {
741 case 'right':
742 break;
743 case 'center':
744 $result[0] = round(($result[0])/2);
745 $result[1] = round(($result[1])/2);
746 break;
747 default:
748 $result[0]=0;
749 $result[1]=0;
750 break;
751 }
752 $result = $this->applyOffset($result,t3lib_div::intExplode(',',$conf['offset']));
753 $result = $this->applyOffset($result,$workArea);
754 return $result;
755 }
756
757 /**
758 * Calculates bounding box information for the TEXT GIFBUILDER object.
759 *
760 * @param array TypoScript array for the TEXT GIFBUILDER object
761 * @return array Array with three keys [0]/[1] being x/y and [2] being the bounding box array
762 * @access private
763 * @see txtPosition(), tslib_gifBuilder::start()
764 */
765 function calcBBox($conf) {
766 $sF = $this->getTextScalFactor($conf);
767 list($spacing,$wordSpacing) = $this->calcWordSpacing($conf, $sF);
768 $theText = $this->recodeString($conf['text']);
769
770 $charInf = $this->ImageTTFBBoxWrapper($conf['fontSize'], $conf['angle'], $conf['fontFile'], $theText, $conf['splitRendering.'],$sF);
771 $theBBoxInfo = $charInf;
772 if ($conf['angle']) {
773 $xArr = Array($charInf[0],$charInf[2],$charInf[4],$charInf[6]);
774 $yArr = Array($charInf[1],$charInf[3],$charInf[5],$charInf[7]);
775 $x=max($xArr)-min($xArr);
776 $y=max($yArr)-min($yArr);
777 } else {
778 $x = ($charInf[2]-$charInf[0]);
779 $y = ($charInf[1]-$charInf[7]);
780 }
781 // Set original lineHeight (used by line breaks):
782 $theBBoxInfo['lineHeight'] = $y;
783
784 if ($spacing || $wordSpacing) { // If any kind of spacing applys, we use this function:
785 $x=0;
786 if (!$spacing && $wordSpacing) {
787 $bits = explode(' ',$theText);
788 while(list(,$word)=each($bits)) {
789 $word.=' ';
790 $wordInf = $this->ImageTTFBBoxWrapper($conf['fontSize'], $conf['angle'], $conf['fontFile'], $word, $conf['splitRendering.'],$sF);
791 $wordW = ($wordInf[2]-$wordInf[0]);
792 $x+=$wordW+$wordSpacing;
793 }
794 } else {
795 $utf8Chars = $this->singleChars($theText);
796 // For each UTF-8 char, do:
797 foreach($utf8Chars as $char) {
798 $charInf = $this->ImageTTFBBoxWrapper($conf['fontSize'], $conf['angle'], $conf['fontFile'], $char, $conf['splitRendering.'],$sF);
799 $charW = ($charInf[2]-$charInf[0]);
800 $x+=$charW+(($char==' ')?$wordSpacing:$spacing);
801 }
802 }
803 } elseif (isset($conf['breakWidth']) && $conf['breakWidth'] && $this->getRenderedTextWidth($conf['text'], $conf) > $conf['breakWidth']) {
804 $maxWidth = 0;
805 $currentWidth = 0;
806 $breakWidth = $conf['breakWidth'];
807 $breakSpace = $this->getBreakSpace($conf, $theBBoxInfo);
808
809 $wordPairs = $this->getWordPairsForLineBreak($conf['text']);
810 // Iterate through all word pairs:
811 foreach ($wordPairs as $index => $wordPair) {
812 $wordWidth = $this->getRenderedTextWidth($wordPair, $conf);
813 if ($index == 0 || $currentWidth + $wordWidth <= $breakWidth) {
814 $currentWidth+= $wordWidth;
815 } else {
816 $maxWidth = max($maxWidth, $currentWidth);
817 $y+= $breakSpace;
818 // Restart:
819 $currentWidth = $wordWidth;
820 }
821 }
822 $x = max($maxWidth, $currentWidth) * $sF;
823 }
824
825 if ($sF > 1) {
826 $x = ceil($x / $sF);
827 $y = ceil($y / $sF);
828 if (is_array($theBBoxInfo)) {
829 foreach ($theBBoxInfo as &$value) {
830 $value = ceil($value / $sF);
831 }
832 }
833 }
834 return array($x, $y, $theBBoxInfo);
835 }
836
837 /**
838 * Adds an <area> tag to the internal variable $this->map which is used to accumulate the content for an ImageMap
839 *
840 * @param array Coordinates for a polygon image map as created by ->calcTextCordsForMap()
841 * @param array Configuration for "imgMap." property of a TEXT GIFBUILDER object.
842 * @return void
843 * @access private
844 * @see makeText(), calcTextCordsForMap()
845 */
846 function addToMap($cords,$conf) {
847 $JS = $conf['noBlur'] ? '' : ' onfocus="blurLink(this);"';
848
849 $this->map.='<area'.
850 ' shape="poly"'.
851 ' coords="'.implode(',',$cords).'"'.
852 ' href="'.htmlspecialchars($conf['url']).'"'.
853 ($conf['target'] ? ' target="'.htmlspecialchars($conf['target']).'"' : '').
854 $JS.
855 (strlen($conf['titleText']) ? ' title="'.htmlspecialchars($conf['titleText']).'"' : '').
856 ' alt="'.htmlspecialchars($conf['altText']).'" />';
857 }
858
859 /**
860 * Calculating the coordinates for a TEXT string on an image map. Used in an <area> tag
861 *
862 * @param array Coordinates (from BBOX array)
863 * @param array Offset array
864 * @param array Configuration for "imgMap." property of a TEXT GIFBUILDER object.
865 * @return array
866 * @access private
867 * @see makeText(), calcTextCordsForMap()
868 */
869 function calcTextCordsForMap($cords,$offset, $conf) {
870 $pars = t3lib_div::intExplode(',',$conf['explode'].',');
871
872 $newCords[0] = $cords[0]+$offset[0]-$pars[0];
873 $newCords[1] = $cords[1]+$offset[1]+$pars[1];
874 $newCords[2] = $cords[2]+$offset[0]+$pars[0];
875 $newCords[3] = $cords[3]+$offset[1]+$pars[1];
876 $newCords[4] = $cords[4]+$offset[0]+$pars[0];
877 $newCords[5] = $cords[5]+$offset[1]-$pars[1];
878 $newCords[6] = $cords[6]+$offset[0]-$pars[0];
879 $newCords[7] = $cords[7]+$offset[1]-$pars[1];
880
881 return $newCords;
882 }
883
884 /**
885 * Printing text onto an image like the PHP function imageTTFText does but in addition it offers options for spacing of letters and words.
886 * Spacing is done by printing one char at a time and this means that the spacing is rather uneven and probably not very nice.
887 * See
888 *
889 * @param pointer (See argument for PHP function imageTTFtext())
890 * @param integer (See argument for PHP function imageTTFtext())
891 * @param integer (See argument for PHP function imageTTFtext())
892 * @param integer (See argument for PHP function imageTTFtext())
893 * @param integer (See argument for PHP function imageTTFtext())
894 * @param integer (See argument for PHP function imageTTFtext())
895 * @param string (See argument for PHP function imageTTFtext())
896 * @param string (See argument for PHP function imageTTFtext()). UTF-8 string, possibly with entities in.
897 * @param integer The spacing of letters in pixels
898 * @param integer The spacing of words in pixels
899 * @param array $splitRenderingConf array
900 * @param integer Scale factor
901 * @return void
902 * @access private
903 */
904 function SpacedImageTTFText(&$im, $fontSize, $angle, $x, $y, $Fcolor, $fontFile, $text, $spacing, $wordSpacing, $splitRenderingConf, $sF=1) {
905
906 $spacing*=$sF;
907 $wordSpacing*=$sF;
908
909 if (!$spacing && $wordSpacing) {
910 $bits = explode(' ',$text);
911 reset($bits);
912 while(list(,$word)=each($bits)) {
913 $word.=' ';
914 $word = $word;
915 $wordInf = $this->ImageTTFBBoxWrapper($fontSize, $angle, $fontFile, $word, $splitRenderingConf ,$sF);
916 $wordW = ($wordInf[2]-$wordInf[0]);
917 $this->ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $Fcolor, $fontFile, $word, $splitRenderingConf, $sF);
918 $x+=$wordW+$wordSpacing;
919 }
920 } else {
921 $utf8Chars = $this->singleChars($text);
922 // For each UTF-8 char, do:
923 foreach($utf8Chars as $char) {
924 $charInf = $this->ImageTTFBBoxWrapper($fontSize, $angle, $fontFile, $char, $splitRenderingConf, $sF);
925 $charW = ($charInf[2]-$charInf[0]);
926 $this->ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $Fcolor, $fontFile, $char, $splitRenderingConf, $sF);
927 $x+=$charW+(($char==' ')?$wordSpacing:$spacing);
928 }
929 }
930 }
931
932 /**
933 * Function that finds the right fontsize that will render the textstring within a certain width
934 *
935 * @param array The TypoScript properties of the TEXT GIFBUILDER object
936 * @return integer The new fontSize
937 * @access private
938 * @author Rene Fritz <r.fritz@colorcube.de>
939 * @see tslib_gifBuilder::start()
940 */
941 function fontResize($conf) {
942 // 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!!!!
943 $maxWidth = intval($conf['maxWidth']);
944 list($spacing,$wordSpacing) = $this->calcWordSpacing($conf);
945 if ($maxWidth) {
946 if ($spacing || $wordSpacing) { // If any kind of spacing applys, we use this function:
947 return $conf['fontSize'];
948 // ################ no calc for spacing yet !!!!!!
949 } else {
950 do {
951 // determine bounding box.
952 $bounds = $this->ImageTTFBBoxWrapper($conf['fontSize'], $conf['angle'], $conf['fontFile'], $this->recodeString($conf['text']), $conf['splitRendering.']);
953 if ($conf['angle']< 0) {
954 $pixelWidth = abs($bounds[4]-$bounds[0]);
955 } elseif ($conf['angle'] > 0) {
956 $pixelWidth = abs($bounds[2]-$bounds[6]);
957 } else {
958 $pixelWidth = abs($bounds[4]-$bounds[6]);
959 }
960
961 // Size is fine, exit:
962 if ($pixelWidth <= $maxWidth) {
963 break;
964 } else {
965 $conf['fontSize']--;
966 }
967 } while ($conf['fontSize']>1);
968 }//if spacing
969 }
970 return $conf['fontSize'];
971 }
972
973 /**
974 * Wrapper for ImageTTFBBox
975 *
976 * @param integer (See argument for PHP function ImageTTFBBox())
977 * @param integer (See argument for PHP function ImageTTFBBox())
978 * @param string (See argument for PHP function ImageTTFBBox())
979 * @param string (See argument for PHP function ImageTTFBBox())
980 * @param array Split-rendering configuration
981 * @param integer Scale factor
982 * @return array Information array.
983 */
984 function ImageTTFBBoxWrapper($fontSize, $angle, $fontFile, $string, $splitRendering, $sF=1) {
985
986 // Initialize:
987 $offsetInfo = array();
988 $stringParts = $this->splitString($string,$splitRendering,$fontSize,$fontFile);
989
990 // Traverse string parts:
991 foreach($stringParts as $strCfg) {
992 $fontFile = t3lib_stdGraphic::prependAbsolutePath($strCfg['fontFile']);
993 if (is_readable($fontFile)) {
994
995 // Calculate Bounding Box for part:
996 $calc = ImageTTFBBox(t3lib_div::freetypeDpiComp($sF*$strCfg['fontSize']), $angle, $fontFile, $strCfg['str']);
997
998 // Calculate offsets:
999 if (!count($offsetInfo)) {
1000 $offsetInfo = $calc; // First run, just copy over.
1001 } else {
1002 $offsetInfo[2]+=$calc[2]-$calc[0]+intval($splitRendering['compX'])+intval($strCfg['xSpaceBefore'])+intval($strCfg['xSpaceAfter']);
1003 $offsetInfo[3]+=$calc[3]-$calc[1]-intval($splitRendering['compY'])-intval($strCfg['ySpaceBefore'])-intval($strCfg['ySpaceAfter']);
1004 $offsetInfo[4]+=$calc[4]-$calc[6]+intval($splitRendering['compX'])+intval($strCfg['xSpaceBefore'])+intval($strCfg['xSpaceAfter']);
1005 $offsetInfo[5]+=$calc[5]-$calc[7]-intval($splitRendering['compY'])-intval($strCfg['ySpaceBefore'])-intval($strCfg['ySpaceAfter']);
1006 }
1007
1008 } else {
1009 debug('cannot read file: '.$fontFile, 't3lib_stdGraphic::ImageTTFBBoxWrapper()');
1010 }
1011 }
1012
1013 return $offsetInfo;
1014 }
1015
1016 /**
1017 * Wrapper for ImageTTFText
1018 *
1019 * @param pointer (See argument for PHP function imageTTFtext())
1020 * @param integer (See argument for PHP function imageTTFtext())
1021 * @param integer (See argument for PHP function imageTTFtext())
1022 * @param integer (See argument for PHP function imageTTFtext())
1023 * @param integer (See argument for PHP function imageTTFtext())
1024 * @param integer (See argument for PHP function imageTTFtext())
1025 * @param string (See argument for PHP function imageTTFtext())
1026 * @param string (See argument for PHP function imageTTFtext()). UTF-8 string, possibly with entities in.
1027 * @param array Split-rendering configuration
1028 * @param integer Scale factor
1029 * @return void
1030 */
1031 function ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $color, $fontFile, $string, $splitRendering,$sF=1) {
1032
1033 // Initialize:
1034 $stringParts = $this->splitString($string,$splitRendering,$fontSize,$fontFile);
1035 $x = ceil($sF*$x);
1036 $y = ceil($sF*$y);
1037
1038 // Traverse string parts:
1039 foreach($stringParts as $i => $strCfg) {
1040
1041 // Initialize:
1042 $colorIndex = $color;
1043
1044 // Set custom color if any (only when niceText is off):
1045 if ($strCfg['color'] && $sF==1) {
1046 $cols = $this->convertColor($strCfg['color']);
1047 $colorIndex = ImageColorAllocate($im, $cols[0],$cols[1],$cols[2]);
1048 $colorIndex = $color >= 0 ? $colorIndex : -$colorIndex;
1049 }
1050
1051 // Setting xSpaceBefore
1052 if ($i) {
1053 $x+= intval($strCfg['xSpaceBefore']);
1054 $y-= intval($strCfg['ySpaceBefore']);
1055 }
1056
1057 $fontFile = t3lib_stdGraphic::prependAbsolutePath($strCfg['fontFile']);
1058 if (is_readable($fontFile)) {
1059
1060 // Render part:
1061 ImageTTFText($im, t3lib_div::freetypeDpiComp($sF*$strCfg['fontSize']), $angle, $x, $y, $colorIndex, $fontFile, $strCfg['str']);
1062
1063 // Calculate offset to apply:
1064 $wordInf = ImageTTFBBox(t3lib_div::freetypeDpiComp($sF*$strCfg['fontSize']), $angle, t3lib_stdGraphic::prependAbsolutePath($strCfg['fontFile']), $strCfg['str']);
1065 $x+= $wordInf[2]-$wordInf[0]+intval($splitRendering['compX'])+intval($strCfg['xSpaceAfter']);
1066 $y+= $wordInf[5]-$wordInf[7]-intval($splitRendering['compY'])-intval($strCfg['ySpaceAfter']);
1067
1068 } else {
1069 debug('cannot read file: '.$fontFile, 't3lib_stdGraphic::ImageTTFTextWrapper()');
1070 }
1071
1072 }
1073 }
1074
1075 /**
1076 * Splitting a string for ImageTTFBBox up into an array where each part has its own configuration options.
1077 *
1078 * @param string UTF-8 string
1079 * @param array Split-rendering configuration from GIFBUILDER TEXT object.
1080 * @param integer Current fontsize
1081 * @param string Current font file
1082 * @return array Array with input string splitted according to configuration
1083 */
1084 function splitString($string,$splitRendering,$fontSize,$fontFile) {
1085
1086 // Initialize by setting the whole string and default configuration as the first entry.
1087 $result = array();
1088 $result[] = array(
1089 'str' => $string,
1090 'fontSize' => $fontSize,
1091 'fontFile' => $fontFile
1092 );
1093
1094 // Traverse the split-rendering configuration:
1095 // Splitting will create more entries in $result with individual configurations.
1096 if (is_array($splitRendering)) {
1097 $sKeyArray = t3lib_TStemplate::sortedKeyList($splitRendering);
1098
1099 // Traverse configured options:
1100 foreach($sKeyArray as $key) {
1101 $cfg = $splitRendering[$key.'.'];
1102
1103 // Process each type of split rendering keyword:
1104 switch((string)$splitRendering[$key]) {
1105 case 'highlightWord':
1106 if (strlen($cfg['value'])) {
1107 $newResult = array();
1108
1109 // Traverse the current parts of the result array:
1110 foreach($result as $part) {
1111 // Explode the string value by the word value to highlight:
1112 $explodedParts = explode($cfg['value'],$part['str']);
1113 foreach($explodedParts as $c => $expValue) {
1114 if (strlen($expValue)) {
1115 $newResult[] = array_merge($part,array('str' => $expValue));
1116 }
1117 if ($c+1 < count($explodedParts)) {
1118 $newResult[] = array(
1119 'str' => $cfg['value'],
1120 'fontSize' => $cfg['fontSize'] ? $cfg['fontSize'] : $part['fontSize'],
1121 'fontFile' => $cfg['fontFile'] ? $cfg['fontFile'] : $part['fontFile'],
1122 'color' => $cfg['color'],
1123 'xSpaceBefore' => $cfg['xSpaceBefore'],
1124 'xSpaceAfter' => $cfg['xSpaceAfter'],
1125 'ySpaceBefore' => $cfg['ySpaceBefore'],
1126 'ySpaceAfter' => $cfg['ySpaceAfter'],
1127 );
1128 }
1129 }
1130 }
1131
1132 // Set the new result as result array:
1133 if (count($newResult)) {
1134 $result = $newResult;
1135 }
1136 }
1137 break;
1138 case 'charRange':
1139 if (strlen($cfg['value'])) {
1140
1141 // Initialize range:
1142 $ranges = t3lib_div::trimExplode(',',$cfg['value'],1);
1143 foreach($ranges as $i => $rangeDef) {
1144 $ranges[$i] = t3lib_div::intExplode('-',$ranges[$i]);
1145 if (!isset($ranges[$i][1])) $ranges[$i][1] = $ranges[$i][0];
1146 }
1147 $newResult = array();
1148
1149 // Traverse the current parts of the result array:
1150 foreach($result as $part) {
1151
1152 // Initialize:
1153 $currentState = -1;
1154 $bankAccum = '';
1155
1156 // Explode the string value by the word value to highlight:
1157 $utf8Chars = $this->singleChars($part['str']);
1158 foreach($utf8Chars as $utfChar) {
1159
1160 // Find number and evaluate position:
1161 $uNumber = $this->csConvObj->utf8CharToUnumber($utfChar);
1162 $inRange = 0;
1163 foreach($ranges as $rangeDef) {
1164 if ($uNumber >= $rangeDef[0] && (!$rangeDef[1] || $uNumber <= $rangeDef[1])) {
1165 $inRange = 1;
1166 break;
1167 }
1168 }
1169 if ($currentState==-1) $currentState = $inRange; // Initialize first char
1170
1171 // Switch bank:
1172 if ($inRange != $currentState && !t3lib_div::inList('32,10,13,9',$uNumber)) {
1173
1174 // Set result:
1175 if (strlen($bankAccum)) {
1176 $newResult[] = array(
1177 'str' => $bankAccum,
1178 'fontSize' => $currentState && $cfg['fontSize'] ? $cfg['fontSize'] : $part['fontSize'],
1179 'fontFile' => $currentState && $cfg['fontFile'] ? $cfg['fontFile'] : $part['fontFile'],
1180 'color' => $currentState ? $cfg['color'] : '',
1181 'xSpaceBefore' => $currentState ? $cfg['xSpaceBefore'] : '',
1182 'xSpaceAfter' => $currentState ? $cfg['xSpaceAfter'] : '',
1183 'ySpaceBefore' => $currentState ? $cfg['ySpaceBefore'] : '',
1184 'ySpaceAfter' => $currentState ? $cfg['ySpaceAfter'] : '',
1185 );
1186 }
1187
1188 // Initialize new settings:
1189 $currentState = $inRange;
1190 $bankAccum = '';
1191 }
1192
1193 // Add char to bank:
1194 $bankAccum.=$utfChar;
1195 }
1196
1197 // Set result for FINAL part:
1198 if (strlen($bankAccum)) {
1199 $newResult[] = array(
1200 'str' => $bankAccum,
1201 'fontSize' => $currentState && $cfg['fontSize'] ? $cfg['fontSize'] : $part['fontSize'],
1202 'fontFile' => $currentState && $cfg['fontFile'] ? $cfg['fontFile'] : $part['fontFile'],
1203 'color' => $currentState ? $cfg['color'] : '',
1204 'xSpaceBefore' => $currentState ? $cfg['xSpaceBefore'] : '',
1205 'xSpaceAfter' => $currentState ? $cfg['xSpaceAfter'] : '',
1206 'ySpaceBefore' => $currentState ? $cfg['ySpaceBefore'] : '',
1207 'ySpaceAfter' => $currentState ? $cfg['ySpaceAfter'] : '',
1208 );
1209 }
1210 }
1211
1212 // Set the new result as result array:
1213 if (count($newResult)) {
1214 $result = $newResult;
1215 }
1216 }
1217 break;
1218 }
1219 }
1220 }
1221
1222 return $result;
1223 }
1224
1225 /**
1226 * Calculates the spacing and wordSpacing values
1227 *
1228 * @param array TypoScript array for the TEXT GIFBUILDER object
1229 * @param integer TypoScript value from eg $conf['niceText.']['scaleFactor']
1230 * @return array Array with two keys [0]/[1] being array($spacing,$wordSpacing)
1231 * @access private
1232 * @see calcBBox()
1233 */
1234 function calcWordSpacing($conf, $scaleFactor=1) {
1235
1236 $spacing = intval($conf['spacing']);
1237 $wordSpacing = intval($conf['wordSpacing']);
1238 $wordSpacing = $wordSpacing?$wordSpacing:$spacing*2;
1239
1240 $spacing*=$scaleFactor;
1241 $wordSpacing*=$scaleFactor;
1242
1243 return array($spacing,$wordSpacing);
1244 }
1245
1246 /**
1247 * Calculates and returns the niceText.scaleFactor
1248 *
1249 * @param array TypoScript array for the TEXT GIFBUILDER object
1250 * @return integer TypoScript value from eg $conf['niceText.']['scaleFactor']
1251 * @access private
1252 */
1253 function getTextScalFactor($conf) {
1254 if (!$conf['niceText']) {
1255 $sF = 1;
1256 } else { // NICETEXT::
1257 $sF = t3lib_div::intInRange($conf['niceText.']['scaleFactor'],2,5);
1258 }
1259 return $sF;
1260 }
1261
1262 /**
1263 * Renders a regular text and takes care of a possible line break automatically.
1264 *
1265 * @param pointer (See argument for PHP function imageTTFtext())
1266 * @param integer (See argument for PHP function imageTTFtext())
1267 * @param integer (See argument for PHP function imageTTFtext())
1268 * @param integer (See argument for PHP function imageTTFtext())
1269 * @param integer (See argument for PHP function imageTTFtext())
1270 * @param integer (See argument for PHP function imageTTFtext())
1271 * @param string (See argument for PHP function imageTTFtext())
1272 * @param string (See argument for PHP function imageTTFtext()). UTF-8 string, possibly with entities in.
1273 * @param array Split-rendering configuration
1274 * @param integer Scale factor
1275 * @param array $conf: The configuration
1276 * @return void
1277 */
1278 protected function renderTTFText(&$im, $fontSize, $angle, $x, $y, $color, $fontFile, $string, $splitRendering, $conf, $sF = 1) {
1279 if (isset($conf['breakWidth']) && $conf['breakWidth'] && $this->getRenderedTextWidth($string, $conf) > $conf['breakWidth']) {
1280 $phrase = '';
1281 $currentWidth = 0;
1282
1283 $breakWidth = $conf['breakWidth'];
1284 $breakSpace = $this->getBreakSpace($conf);
1285
1286 $wordPairs = $this->getWordPairsForLineBreak($string);
1287 // Iterate through all word pairs:
1288 foreach ($wordPairs as $index => $wordPair) {
1289 $wordWidth = $this->getRenderedTextWidth($wordPair, $conf);
1290 if ($index == 0 || $currentWidth + $wordWidth <= $breakWidth) {
1291 $currentWidth+= $wordWidth;
1292 $phrase.= $wordPair;
1293 } else {
1294 // Render the current phrase that is below breakWidth:
1295 $this->ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $color, $fontFile, $phrase, $splitRendering, $sF);
1296 // Calculate the news height offset:
1297 $y+= $breakSpace;
1298 // Restart the phrase:
1299 $currentWidth = $wordWidth;
1300 $phrase = $wordPair;
1301 }
1302 }
1303 // Render the remaining phrase:
1304 if ($currentWidth) {
1305 $this->ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $color, $fontFile, $phrase, $splitRendering, $sF);
1306 }
1307 } else {
1308 $this->ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $color, $fontFile, $string, $splitRendering, $sF);
1309 }
1310 }
1311
1312 /**
1313 * Gets the word pairs used for automatic line breaks.
1314 *
1315 * @param string $string
1316 * @return array
1317 */
1318 protected function getWordPairsForLineBreak($string) {
1319 $wordPairs = array();
1320
1321 $wordsArray = preg_split('#([ -.,!:]+)#', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
1322 $wordsCount = count($wordsArray);
1323 for ($index=0; $index < $wordsCount; $index+= 2) {
1324 $wordPairs[] = $wordsArray[$index] . $wordsArray[$index + 1];
1325 }
1326
1327 return $wordPairs;
1328 }
1329
1330 /**
1331 * Gets the rendered text width.
1332 *
1333 * @param string $text
1334 * @param array $conf
1335 * @param integer
1336 */
1337 protected function getRenderedTextWidth($text, $conf) {
1338 $bounds = $this->ImageTTFBBoxWrapper($conf['fontSize'], $conf['angle'], $conf['fontFile'], $this->recodeString($text), $conf['splitRendering.']);
1339 if ($conf['angle']< 0) {
1340 $pixelWidth = abs($bounds[4]-$bounds[0]);
1341 } elseif ($conf['angle'] > 0) {
1342 $pixelWidth = abs($bounds[2]-$bounds[6]);
1343 } else {
1344 $pixelWidth = abs($bounds[4]-$bounds[6]);
1345 }
1346 return $pixelWidth;
1347 }
1348
1349 /**
1350 * Gets the break space for each new line.
1351 *
1352 * @param array $conf: TypoScript configuration for the currently rendered object
1353 * @param array $boundingBox: The bounding box the the currently rendered object
1354 * @return integer The break space
1355 */
1356 protected function getBreakSpace($conf, array $boundingBox = NULL) {
1357 if (!isset($boundingBox)) {
1358 $boundingBox = $this->calcBBox($conf);
1359 $boundingBox = $boundingBox[2];
1360 }
1361
1362 if (isset($conf['breakSpace']) && $conf['breakSpace']) {
1363 $breakSpace = $boundingBox['lineHeight'] * $conf['breakSpace'];
1364 } else {
1365 $breakSpace = $boundingBox['lineHeight'];
1366 }
1367
1368 return $breakSpace;
1369 }
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381 /*********************************************
1382 *
1383 * Other GIFBUILDER objects related to TEXT
1384 *
1385 *********************************************/
1386
1387 /**
1388 * Implements the "OUTLINE" GIFBUILDER object / property for the TEXT object
1389 *
1390 * @param pointer GDlib image pointer
1391 * @param array TypoScript array with configuration for the GIFBUILDER object.
1392 * @param array The current working area coordinates.
1393 * @param array TypoScript array with configuration for the associated TEXT GIFBUILDER object.
1394 * @return void
1395 * @see tslib_gifBuilder::make(), makeText()
1396 */
1397 function makeOutline(&$im,$conf,$workArea,$txtConf) {
1398 $thickness = intval($conf['thickness']);
1399 if ($thickness) {
1400 $txtConf['fontColor'] = $conf['color'];
1401 $outLineDist = t3lib_div::intInRange($thickness,1,2);
1402 for ($b=1;$b<=$outLineDist;$b++) {
1403 if ($b==1) {
1404 $it = 8;
1405 } else {
1406 $it = 16;
1407 }
1408 $outL = $this->circleOffset($b, $it);
1409 for ($a=0;$a<$it;$a++) {
1410 $this->makeText($im,$txtConf,$this->applyOffset($workArea,$outL[$a]));
1411 }
1412 }
1413 }
1414 }
1415
1416 /**
1417 * Creates some offset values in an array used to simulate a circularly applied outline around TEXT
1418 *
1419 * access private
1420 *
1421 * @param integer Distance
1422 * @param integer Iterations.
1423 * @return array
1424 * @see makeOutline()
1425 */
1426 function circleOffset($distance, $iterations) {
1427 $res = Array();
1428 if ($distance && $iterations) {
1429 for ($a=0;$a<$iterations;$a++) {
1430 $yOff = round(sin(2*pi()/$iterations*($a+1))*100*$distance);
1431 if ($yOff) {$yOff = intval(ceil(abs($yOff/100))*($yOff/abs($yOff)));}
1432 $xOff = round(cos(2*pi()/$iterations*($a+1))*100*$distance);
1433 if ($xOff) {$xOff = intval(ceil(abs($xOff/100))*($xOff/abs($xOff)));}
1434 $res[$a] = Array($xOff,$yOff);
1435 }
1436 }
1437 return $res;
1438 }
1439
1440 /**
1441 * Implements the "EMBOSS" GIFBUILDER object / property for the TEXT object
1442 *
1443 * @param pointer GDlib image pointer
1444 * @param array TypoScript array with configuration for the GIFBUILDER object.
1445 * @param array The current working area coordinates.
1446 * @param array TypoScript array with configuration for the associated TEXT GIFBUILDER object.
1447 * @return void
1448 * @see tslib_gifBuilder::make(), makeShadow()
1449 */
1450 function makeEmboss(&$im,$conf,$workArea,$txtConf) {
1451 $conf['color']=$conf['highColor'];
1452 $this->makeShadow($im,$conf,$workArea,$txtConf);
1453 $newOffset = t3lib_div::intExplode(',',$conf['offset']);
1454 $newOffset[0]*=-1;
1455 $newOffset[1]*=-1;
1456 $conf['offset']=implode(',',$newOffset);
1457 $conf['color']=$conf['lowColor'];
1458 $this->makeShadow($im,$conf,$workArea,$txtConf);
1459 }
1460
1461 /**
1462 * Implements the "SHADOW" GIFBUILDER object / property for the TEXT object
1463 * The operation involves ImageMagick for combining.
1464 *
1465 * @param pointer GDlib image pointer
1466 * @param array TypoScript array with configuration for the GIFBUILDER object.
1467 * @param array The current working area coordinates.
1468 * @param array TypoScript array with configuration for the associated TEXT GIFBUILDER object.
1469 * @return void
1470 * @see tslib_gifBuilder::make(), makeText(), makeEmboss()
1471 */
1472 function makeShadow(&$im,$conf,$workArea,$txtConf) {
1473 $workArea = $this->applyOffset($workArea,t3lib_div::intExplode(',',$conf['offset']));
1474 $blurRate = t3lib_div::intInRange(intval($conf['blur']),0,99);
1475
1476 if (!$blurRate || $this->NO_IM_EFFECTS) { // No effects if ImageMagick ver. 5+
1477 $txtConf['fontColor'] = $conf['color'];
1478 $this->makeText($im,$txtConf,$workArea);
1479 } else {
1480 $w = imagesx($im);
1481 $h = imagesy($im);
1482 $blurBorder= 3; // area around the blur used for cropping something
1483 $tmpStr = $this->randomName();
1484 $fileMenu = $tmpStr.'_menu.'.$this->gifExtension;
1485 $fileColor = $tmpStr.'_color.'.$this->gifExtension;
1486 $fileMask = $tmpStr.'_mask.'.$this->gifExtension;
1487
1488 // BlurColor Image laves
1489 $blurColImg = $this->imagecreate($w,$h);
1490 $bcols=$this->convertColor($conf['color']);
1491 $Bcolor = ImageColorAllocate($blurColImg, $bcols[0],$bcols[1],$bcols[2]);
1492 ImageFilledRectangle($blurColImg, 0, 0, $w, $h, $Bcolor);
1493 $this->ImageWrite($blurColImg, $fileColor);
1494 ImageDestroy($blurColImg);
1495
1496 // The mask is made: BlurTextImage
1497 $blurTextImg = $this->imagecreate($w+$blurBorder*2,$h+$blurBorder*2);
1498 $Bcolor = ImageColorAllocate($blurTextImg, 0,0,0); // black background
1499 ImageFilledRectangle($blurTextImg, 0, 0, $w+$blurBorder*2, $h+$blurBorder*2, $Bcolor);
1500 $txtConf['fontColor'] = 'white';
1501 $blurBordArr = Array($blurBorder,$blurBorder);
1502 $this->makeText($blurTextImg,$txtConf, $this->applyOffset($workArea,$blurBordArr));
1503 $this->ImageWrite($blurTextImg, $fileMask); // dump to temporary file
1504 ImageDestroy($blurTextImg); // destroy
1505
1506
1507 $command='';
1508 $command.=$this->maskNegate;
1509
1510 if ($this->V5_EFFECTS) {
1511 $command.=$this->v5_blur($blurRate+1);
1512 } else {
1513 // Blurring of the mask
1514 $times = ceil($blurRate/10); // How many blur-commands that is executed. Min = 1;
1515 $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.
1516 $newBlurRate = t3lib_div::intInRange($newBlurRate,1,99);
1517 for ($a=0;$a<$times;$a++) { // Building blur-command
1518 $command.=' -blur '.$blurRate;
1519 }
1520 }
1521
1522 $this->imageMagickExec($fileMask,$fileMask,$command.' +matte');
1523
1524 $blurTextImg_tmp = $this->imageCreateFromFile($fileMask); // the mask is loaded again
1525 if ($blurTextImg_tmp) { // if nothing went wrong we continue with the blurred mask
1526
1527 // cropping the border from the mask
1528 $blurTextImg = $this->imagecreate($w,$h);
1529 $this->imagecopyresized($blurTextImg, $blurTextImg_tmp, 0, 0, $blurBorder, $blurBorder, $w, $h, $w, $h);
1530 ImageDestroy($blurTextImg_tmp); // Destroy the temporary mask
1531
1532 // adjust the mask
1533 $intensity = 40;
1534 if ($conf['intensity']) {
1535 $intensity = t3lib_div::intInRange($conf['intensity'],0,100);
1536 }
1537 $intensity = ceil(255-($intensity/100*255));
1538 $this->inputLevels($blurTextImg,0,$intensity,$this->maskNegate);
1539
1540 $opacity = t3lib_div::intInRange(intval($conf['opacity']),0,100);
1541 if ($opacity && $opacity<100) {
1542 $high = ceil(255*$opacity/100);
1543 $this->outputLevels($blurTextImg,0,$high,$this->maskNegate); // reducing levels as the opacity demands
1544 }
1545
1546 $this->ImageWrite($blurTextImg, $fileMask); // Dump the mask again
1547 ImageDestroy($blurTextImg); // Destroy the mask
1548
1549 // The pictures are combined
1550 $this->ImageWrite($im, $fileMenu); // The main pictures is saved temporarily
1551
1552 $this->combineExec($fileMenu,$fileColor,$fileMask,$fileMenu);
1553
1554 $backIm = $this->imageCreateFromFile($fileMenu); // The main image is loaded again...
1555 if ($backIm) { // ... and if nothing went wrong we load it onto the old one.
1556 ImageColorTransparent($backIm,-1);
1557 $im = $backIm;
1558 }
1559 }
1560 // Deleting temporary files;
1561 if (!$this->dontUnlinkTempFiles) {
1562 unlink($fileMenu);
1563 unlink($fileColor);
1564 unlink($fileMask);
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 * Other GIFBUILDER objects
1592 *
1593 ****************************/
1594
1595 /**
1596 * Implements the "BOX" GIFBUILDER object
1597 *
1598 * @param pointer GDlib image pointer
1599 * @param array TypoScript array with configuration for the GIFBUILDER object.
1600 * @param array The current working area coordinates.
1601 * @return void
1602 * @see tslib_gifBuilder::make()
1603 */
1604 function makeBox(&$im,$conf,$workArea) {
1605 $cords = t3lib_div::intExplode(',',$conf['dimensions'].',,,');
1606 $conf['offset']=$cords[0].','.$cords[1];
1607 $cords = $this->objPosition($conf,$workArea,Array($cords[2],$cords[3]));
1608 $cols=$this->convertColor($conf['color']);
1609 if (!$this->truecolor) {
1610 $reduce = t3lib_div::intInRange($this->setup['reduceColors'], 256, $this->truecolorColors, 256);
1611 $this->reduceColors($im, $reduce-1, $reduce-2); // If "reduce-1" colors (or more) are used reduce them to "reduce-2"
1612 }
1613
1614 $opacity = 0;
1615 if (isset($conf['opacity'])) {
1616 // conversion:
1617 // PHP 0 = opaque, 127 = transparent
1618 // TYPO3 100 = opaque, 0 = transparent
1619 $opacity = t3lib_div::intInRange(intval($conf['opacity']), 1, 100, 1);
1620 $opacity = abs($opacity - 100);
1621 $opacity = round((127 * $opacity) / 100);
1622 }
1623
1624 $tmpColor = ImageColorAllocateAlpha($im, $cols[0],$cols[1],$cols[2], $opacity);
1625 imagefilledrectangle($im, $cords[0], $cords[1], $cords[0]+$cords[2]-1, $cords[1]+$cords[3]-1, $tmpColor);
1626 }
1627
1628 /**
1629 * Implements the "EFFECT" GIFBUILDER object
1630 * The operation involves ImageMagick for applying effects
1631 *
1632 * @param pointer GDlib image pointer
1633 * @param array TypoScript array with configuration for the GIFBUILDER object.
1634 * @return void
1635 * @see tslib_gifBuilder::make(), applyImageMagickToPHPGif()
1636 */
1637 function makeEffect(&$im, $conf) {
1638 $commands = $this->IMparams($conf['value']);
1639 if ($commands) {
1640 $this->applyImageMagickToPHPGif($im, $commands);
1641 }
1642 }
1643
1644 /**
1645 * Creating ImageMagick paramters from TypoScript property
1646 *
1647 * @param string A string with effect keywords=value pairs separated by "|"
1648 * @return string ImageMagick prepared parameters.
1649 * @access private
1650 * @see makeEffect()
1651 */
1652 function IMparams($setup) {
1653 if (!trim($setup)){return '';}
1654 $effects = explode('|', $setup);
1655 $commands = '';
1656 while(list(,$val)=each($effects)) {
1657 $pairs=explode('=',$val,2);
1658 $value = trim($pairs[1]);
1659 $effect = strtolower(trim($pairs[0]));
1660 switch($effect) {
1661 case 'gamma':
1662 $commands.=' -gamma '.doubleval($value);
1663 break;
1664 case 'blur':
1665 if (!$this->NO_IM_EFFECTS) {
1666 if ($this->V5_EFFECTS) {
1667 $commands.=$this->v5_blur($value);
1668 } else {
1669 $commands.=' -blur '.t3lib_div::intInRange($value,1,99);
1670 }
1671 }
1672 break;
1673 case 'sharpen':
1674 if (!$this->NO_IM_EFFECTS) {
1675 if ($this->V5_EFFECTS) {
1676 $commands.=$this->v5_sharpen($value);
1677 } else {
1678 $commands.=' -sharpen '.t3lib_div::intInRange($value,1,99);
1679 }
1680 }
1681 break;
1682 case 'rotate':
1683 $commands.=' -rotate '.t3lib_div::intInRange($value,0,360);
1684 break;
1685 case 'solarize':
1686 $commands.=' -solarize '.t3lib_div::intInRange($value,0,99);
1687 break;
1688 case 'swirl':
1689 $commands.=' -swirl '.t3lib_div::intInRange($value,0,1000);
1690 break;
1691 case 'wave':
1692 $params = t3lib_div::intExplode(',',$value);
1693 $commands.=' -wave '.t3lib_div::intInRange($params[0],0,99).'x'.t3lib_div::intInRange($params[1],0,99);
1694 break;
1695 case 'charcoal':
1696 $commands.=' -charcoal '.t3lib_div::intInRange($value,0,100);
1697 break;
1698 case 'gray':
1699 $commands.=' -colorspace GRAY';
1700 break;
1701 case 'edge':
1702 $commands.=' -edge '.t3lib_div::intInRange($value,0,99);
1703 break;
1704 case 'emboss':
1705 $commands.=' -emboss';
1706 break;
1707 case 'flip':
1708 $commands.=' -flip';
1709 break;
1710 case 'flop':
1711 $commands.=' -flop';
1712 break;
1713 case 'colors':
1714 $commands.=' -colors '.t3lib_div::intInRange($value,2,255);
1715 break;
1716 case 'shear':
1717 $commands.=' -shear '.t3lib_div::intInRange($value,-90,90);
1718 break;
1719 case 'invert':
1720 $commands.=' -negate';
1721 break;
1722 }
1723 }
1724 return $commands;
1725 }
1726
1727 /**
1728 * Implements the "ADJUST" GIFBUILDER object
1729 *
1730 * @param pointer GDlib image pointer
1731 * @param array TypoScript array with configuration for the GIFBUILDER object.
1732 * @return void
1733 * @see tslib_gifBuilder::make(), autoLevels(), outputLevels(), inputLevels()
1734 */
1735 function adjust(&$im, $conf) {
1736 $setup = $conf['value'];
1737 if (!trim($setup)){return '';}
1738 $effects = explode('|', $setup);
1739 while(list(,$val)=each($effects)) {
1740 $pairs=explode('=',$val,2);
1741 $value = trim($pairs[1]);
1742 $effect = strtolower(trim($pairs[0]));
1743 switch($effect) {
1744 case 'inputlevels': // low,high
1745 $params = t3lib_div::intExplode(',',$value);
1746 $this->inputLevels($im,$params[0],$params[1]);
1747 break;
1748 case 'outputlevels':
1749 $params = t3lib_div::intExplode(',',$value);
1750 $this->outputLevels($im,$params[0],$params[1]);
1751 break;
1752 case 'autolevels':
1753 $this->autoLevels($im);
1754 break;
1755 }
1756 }
1757 }
1758
1759 /**
1760 * Implements the "CROP" GIFBUILDER object
1761 *
1762 * @param pointer GDlib image pointer
1763 * @param array TypoScript array with configuration for the GIFBUILDER object.
1764 * @return void
1765 * @see tslib_gifBuilder::make()
1766 */
1767 function crop(&$im,$conf) {
1768 $this->setWorkArea(''); // clears workArea to total image
1769 $cords = t3lib_div::intExplode(',',$conf['crop'].',,,');
1770 $conf['offset']=$cords[0].','.$cords[1];
1771 $cords = $this->objPosition($conf,$this->workArea,Array($cords[2],$cords[3]));
1772
1773 $newIm = $this->imagecreate($cords[2],$cords[3]);
1774 $cols=$this->convertColor($conf['backColor']?$conf['backColor']:$this->setup['backColor']);
1775 $Bcolor = ImageColorAllocate($newIm, $cols[0],$cols[1],$cols[2]);
1776 ImageFilledRectangle($newIm, 0, 0, $cords[2], $cords[3], $Bcolor);
1777
1778 $newConf = Array();
1779 $workArea = Array(0,0,$cords[2],$cords[3]);
1780 if ($cords[0]<0) {$workArea[0]=abs($cords[0]);} else {$newConf['offset']=-$cords[0];}
1781 if ($cords[1]<0) {$workArea[1]=abs($cords[1]);} else {$newConf['offset'].=','.-$cords[1];}
1782
1783 $this->copyGifOntoGif($newIm,$im,$newConf,$workArea);
1784 $im = $newIm;
1785 $this->w = imagesx($im);
1786 $this->h = imagesy($im);
1787 $this->setWorkArea(''); // clears workArea to total image
1788 }
1789
1790 /**
1791 * Implements the "SCALE" GIFBUILDER object
1792 *
1793 * @param pointer GDlib image pointer
1794 * @param array TypoScript array with configuration for the GIFBUILDER object.
1795 * @return void
1796 * @see tslib_gifBuilder::make()
1797 */
1798 function scale(&$im,$conf) {
1799 if ($conf['width'] || $conf['height'] || $conf['params']) {
1800 $tmpStr = $this->randomName();
1801 $theFile = $tmpStr.'.'.$this->gifExtension;
1802 $this->ImageWrite($im, $theFile);
1803 $theNewFile = $this->imageMagickConvert($theFile,$this->gifExtension,$conf['width'],$conf['height'],$conf['params'],'','');
1804 $tmpImg = $this->imageCreateFromFile($theNewFile[3]);
1805 if ($tmpImg) {
1806 ImageDestroy($im);
1807 $im = $tmpImg;
1808 $this->w = imagesx($im);
1809 $this->h = imagesy($im);
1810 $this->setWorkArea(''); // clears workArea to total image
1811 }
1812 if (!$this->dontUnlinkTempFiles) {
1813 unlink($theFile);
1814 if ($theNewFile[3] && $theNewFile[3]!=$theFile) {
1815 unlink($theNewFile[3]);
1816 }
1817 }
1818 }
1819 }
1820
1821 /**
1822 * Implements the "WORKAREA" GIFBUILDER object when setting it
1823 * Setting internal working area boundaries (->workArea)
1824 *
1825 * @param string Working area dimensions, comma separated
1826 * @return void
1827 * @access private
1828 * @see tslib_gifBuilder::make()
1829 */
1830 function setWorkArea($workArea) {
1831 $this->workArea = t3lib_div::intExplode(',',$workArea);
1832 $this->workArea = $this->applyOffset($this->workArea,$this->OFFSET);
1833 if (!$this->workArea[2]) {$this->workArea[2]=$this->w;}
1834 if (!$this->workArea[3]) {$this->workArea[3]=$this->h;}
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 * Adjustment functions
1862 *
1863 ************************/
1864
1865 /**
1866 * Apply auto-levels to input image pointer
1867 *
1868 * @param integer GDlib Image Pointer
1869 * @return void
1870 */
1871 function autolevels(&$im) {
1872 $totalCols = ImageColorsTotal($im);
1873 $min=255;
1874 $max=0;
1875 for ($c=0; $c<$totalCols; $c++) {
1876 $cols = ImageColorsForIndex($im,$c);
1877 $grayArr[] = round(($cols['red']+$cols['green']+$cols['blue'])/3);
1878 }
1879 $min=min($grayArr);
1880 $max=max($grayArr);
1881 $delta = $max-$min;
1882 if ($delta) {
1883 for ($c=0; $c<$totalCols; $c++) {
1884 $cols = ImageColorsForIndex($im,$c);
1885 $cols['red'] = floor(($cols['red']-$min)/$delta*255);
1886 $cols['green'] = floor(($cols['green']-$min)/$delta*255);
1887 $cols['blue'] = floor(($cols['blue']-$min)/$delta*255);
1888 ImageColorSet($im,$c,$cols['red'],$cols['green'],$cols['blue']);
1889 }
1890 }
1891 }
1892
1893 /**
1894 * Apply output levels to input image pointer (decreasing contrast)
1895 *
1896 * @param integer GDlib Image Pointer
1897 * @param integer The "low" value (close to 0)
1898 * @param integer The "high" value (close to 255)
1899 * @param boolean If swap, then low and high are swapped. (Useful for negated masks...)
1900 * @return void
1901 */
1902 function outputLevels(&$im,$low,$high,$swap='') {
1903 if ($low<$high){
1904 $low = t3lib_div::intInRange($low,0,255);
1905 $high = t3lib_div::intInRange($high,0,255);
1906
1907 if ($swap) {
1908 $temp = $low;
1909 $low = 255-$high;
1910 $high = 255-$temp;
1911 }
1912
1913 $delta = $high-$low;
1914 $totalCols = ImageColorsTotal($im);
1915 for ($c=0; $c<$totalCols; $c++) {
1916 $cols = ImageColorsForIndex($im,$c);
1917 $cols['red'] = $low+floor($cols['red']/255*$delta);
1918 $cols['green'] = $low+floor($cols['green']/255*$delta);
1919 $cols['blue'] = $low+floor($cols['blue']/255*$delta);
1920 ImageColorSet($im,$c,$cols['red'],$cols['green'],$cols['blue']);
1921 }
1922 }
1923 }
1924
1925 /**
1926 * Apply input levels to input image pointer (increasing contrast)
1927 *
1928 * @param integer GDlib Image Pointer
1929 * @param integer The "low" value (close to 0)
1930 * @param integer The "high" value (close to 255)
1931 * @param boolean If swap, then low and high are swapped. (Useful for negated masks...)
1932 * @return void
1933 */
1934 function inputLevels(&$im,$low,$high,$swap='') {
1935 if ($low<$high){
1936 $low = t3lib_div::intInRange($low,0,255);
1937 $high = t3lib_div::intInRange($high,0,255);
1938
1939 if ($swap) {
1940 $temp = $low;
1941 $low = 255-$high;
1942 $high = 255-$temp;
1943 }
1944
1945 $delta = $high-$low;
1946 $totalCols = ImageColorsTotal($im);
1947 for ($c=0; $c<$totalCols; $c++) {
1948 $cols = ImageColorsForIndex($im,$c);
1949 $cols['red'] = t3lib_div::intInRange(($cols['red']-$low)/$delta*255, 0,255);
1950 $cols['green'] = t3lib_div::intInRange(($cols['green']-$low)/$delta*255, 0,255);
1951 $cols['blue'] = t3lib_div::intInRange(($cols['blue']-$low)/$delta*255, 0,255);
1952 ImageColorSet($im,$c,$cols['red'],$cols['green'],$cols['blue']);
1953 }
1954 }
1955 }
1956
1957 /**
1958 * Reduce colors in image dependend on the actual amount of colors (Only works if we are not in truecolor mode)
1959 *
1960 * @param integer GDlib Image Pointer
1961 * @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.
1962 * @param integer Number of colors to reduce the image to.
1963 * @return void
1964 */
1965 function reduceColors(&$im,$limit, $cols) {
1966 if (!$this->truecolor && ImageColorsTotal($im)>=$limit) {
1967 $this->makeEffect($im, Array('value'=>'colors='.$cols) );
1968 }
1969 }
1970
1971 /**
1972 * Reduce colors in image using IM and create a palette based image if possible (<=256 colors)
1973 *
1974 * @param string Image file to reduce
1975 * @param integer Number of colors to reduce the image to.
1976 * @return string Reduced file
1977 */
1978 function IMreduceColors($file, $cols) {
1979 $fI = t3lib_div::split_fileref($file);
1980 $ext = strtolower($fI['fileext']);
1981 $result = $this->randomName().'.'.$ext;
1982 if (($reduce = t3lib_div::intInRange($cols, 0, ($ext=='gif'?256:$this->truecolorColors), 0))>0) {
1983 $params = ' -colors '.$reduce;
1984 if (!$this->im_version_4) {
1985 // IM4 doesn't have this options but forces them automatically if applicaple (<256 colors in image)
1986 if ($reduce<=256) { $params .= ' -type Palette'; }
1987 if ($ext=='png' && $reduce<=256) { $prefix = 'png8:'; }
1988 }
1989 $this->imageMagickExec($file, $prefix.$result, $params);
1990 if ($result) {
1991 return $result;
1992 }
1993 }
1994 return '';
1995 }
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007 /*********************************
2008 *
2009 * GIFBUILDER Helper functions
2010 *
2011 *********************************/
2012
2013 /**
2014 * Checks if the $fontFile is already at an absolute path and if not, prepends the correct path.
2015 * Use PATH_site unless we are in the backend.
2016 * Call it by t3lib_stdGraphic::prependAbsolutePath()
2017 *
2018 * @param string The font file
2019 * @return string The font file with absolute path.
2020 */
2021 function prependAbsolutePath($fontFile) {
2022 $absPath = defined('PATH_typo3') ? dirname(PATH_thisScript).'/' :PATH_site;
2023 $fontFile = t3lib_div::isAbsPath($fontFile) ? $fontFile : t3lib_div::resolveBackPath($absPath.$fontFile);
2024 return $fontFile;
2025 }
2026
2027 /**
2028 * Returns the IM command for sharpening with ImageMagick 5 (when $this->V5_EFFECTS is set).
2029 * Uses $this->im5fx_sharpenSteps for translation of the factor to an actual command.
2030 *
2031 * @param integer The sharpening factor, 0-100 (effectively in 10 steps)
2032 * @return string The sharpening command, eg. " -sharpen 3x4"
2033 * @see makeText(), IMparams(), v5_blur()
2034 */
2035 function v5_sharpen($factor) {
2036 $factor = t3lib_div::intInRange(ceil($factor/10),0,10);
2037
2038 $sharpenArr=explode(',',','.$this->im5fx_sharpenSteps);
2039 $sharpenF= trim($sharpenArr[$factor]);
2040 if ($sharpenF) {
2041 $cmd = ' -sharpen '.$sharpenF;
2042 return $cmd;
2043 }
2044 }
2045
2046 /**
2047 * Returns the IM command for blurring with ImageMagick 5 (when $this->V5_EFFECTS is set).
2048 * Uses $this->im5fx_blurSteps for translation of the factor to an actual command.
2049 *
2050 * @param integer The blurring factor, 0-100 (effectively in 10 steps)
2051 * @return string The blurring command, eg. " -blur 3x4"
2052 * @see makeText(), IMparams(), v5_sharpen()
2053 */
2054 function v5_blur($factor) {
2055 $factor = t3lib_div::intInRange(ceil($factor/10),0,10);
2056
2057 $blurArr=explode(',',','.$this->im5fx_blurSteps);
2058 $blurF= trim($blurArr[$factor]);
2059 if ($blurF) {
2060 $cmd=' -blur '.$blurF;
2061 return $cmd;
2062 }
2063 }
2064
2065 /**
2066 * Returns a random filename prefixed with "temp_" and then 32 char md5 hash (without extension) from $this->tempPath.
2067 * 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.
2068 *
2069 * @return string
2070 */
2071 function randomName() {
2072 $this->createTempSubDir('temp/');
2073 return $this->tempPath.'temp/'.md5(uniqid(''));
2074 }
2075
2076 /**
2077 * Applies offset value to coordinated in $cords.
2078 * Basically the value of key 0/1 of $OFFSET is added to keys 0/1 of $cords
2079 *
2080 * @param array Integer coordinates in key 0/1
2081 * @param array Offset values in key 0/1
2082 * @return array Modified $cords array
2083 */
2084 function applyOffset($cords,$OFFSET) {
2085 $cords[0] = intval($cords[0])+intval($OFFSET[0]);
2086 $cords[1] = intval($cords[1])+intval($OFFSET[1]);
2087 return $cords;
2088 }
2089
2090 /**
2091 * Converts a "HTML-color" TypoScript datatype to RGB-values.
2092 * Default is 0,0,0
2093 *
2094 * @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
2095 * @return array RGB values in key 0/1/2 of the array
2096 */
2097 function convertColor($string) {
2098 $col=array();
2099 $cParts = explode(':',$string,2);
2100
2101 // Finding the RGB definitions of the color:
2102 $string=$cParts[0];
2103 if (strstr($string,'#')) {
2104 $string = preg_replace('/[^A-Fa-f0-9]*/','',$string);
2105 $col[]=HexDec(substr($string,0,2));
2106 $col[]=HexDec(substr($string,2,2));
2107 $col[]=HexDec(substr($string,4,2));
2108 } elseif (strstr($string,',')) {
2109 $string = preg_replace('/[^,0-9]*/','',$string);
2110 $strArr = explode(',',$string);
2111 $col[]=intval($strArr[0]);
2112 $col[]=intval($strArr[1]);
2113 $col[]=intval($strArr[2]);
2114 } else {
2115 $string = strtolower(trim($string));
2116 if ($this->colMap[$string]) {
2117 $col = $this->colMap[$string];
2118 } else {
2119 $col = Array(0,0,0);
2120 }
2121 }
2122 // ... and possibly recalculating the value
2123 if (trim($cParts[1])) {
2124 $cParts[1]=trim($cParts[1]);
2125 if (substr($cParts[1],0,1)=='*') {
2126 $val=doubleval(substr($cParts[1],1));
2127 $col[0]=t3lib_div::intInRange($col[0]*$val,0,255);
2128 $col[1]=t3lib_div::intInRange($col[1]*$val,0,255);
2129 $col[2]=t3lib_div::intInRange($col[2]*$val,0,255);
2130 } else {
2131 $val=intval($cParts[1]);
2132 $col[0]=t3lib_div::intInRange($col[0]+$val,0,255);
2133 $col[1]=t3lib_div::intInRange($col[1]+$val,0,255);
2134 $col[2]=t3lib_div::intInRange($col[2]+$val,0,255);
2135 }
2136 }
2137 return $col;
2138 }
2139
2140 /**
2141 * Recode string
2142 * Used with text strings for fonts when languages has other character sets.
2143 *
2144 * @param string The text to recode
2145 * @return string The recoded string. Should be UTF-8 output. MAY contain entities (eg. &#123; or &#quot; which should render as real chars).
2146 */
2147 function recodeString($string) {
2148 // Recode string to UTF-8 from $this->nativeCharset:
2149 if ($this->nativeCharset && $this->nativeCharset!='utf-8') {
2150 $string = $this->csConvObj->utf8_encode($string,$this->nativeCharset); // Convert to UTF-8
2151 }
2152
2153 // Recode string accoding to TTFLocaleConv. Deprecated.
2154 if ($this->TTFLocaleConv) {
2155 list($from, $to) = t3lib_div::trimExplode('..', $this->TTFLocaleConv, true);
2156 $string = $this->csConvObj->conv($string, $from, $to);
2157 }
2158
2159 return $string;
2160 }
2161
2162 /**
2163 * Split a string into an array of individual characters
2164 * 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.
2165 *
2166 * @param string The text string to split
2167 * @param boolean Return Unicode numbers instead of chars.
2168 * @return array Numerical array with a char as each value.
2169 */
2170 function singleChars($theText,$returnUnicodeNumber=FALSE) {
2171 if ($this->nativeCharset) {
2172 return $this->csConvObj->utf8_to_numberarray($theText,1,$returnUnicodeNumber ? 0 : 1); // Get an array of separated UTF-8 chars
2173 } else {
2174 $output=array();
2175 $c=strlen($theText);
2176 for($a=0;$a<$c;$a++) {
2177 $output[]=substr($theText,$a,1);
2178 }
2179 return $output;
2180 }
2181 }
2182
2183 /**
2184 * 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
2185 *
2186 * @param array TypoScript configuration for a GIFBUILDER object
2187 * @param array Workarea definition
2188 * @param array BB (Bounding box) array. Not just used for TEXT objects but also for others
2189 * @return array [0]=x, [1]=y, [2]=w, [3]=h
2190 * @access private
2191 * @see copyGifOntoGif(), makeBox(), crop()
2192 */
2193 function objPosition($conf,$workArea,$BB) {
2194 // offset, align, valign, workarea
2195 $result=Array();
2196 $result[2] = $BB[0];
2197 $result[3] = $BB[1];
2198 $w=$workArea[2];
2199 $h=$workArea[3];
2200
2201 $align = explode(',',$conf['align']);
2202 $align[0] = strtolower(substr(trim($align[0]),0,1));
2203 $align[1] = strtolower(substr(trim($align[1]),0,1));
2204
2205 switch($align[0]) {
2206 case 'r':
2207 $result[0]=$w-$result[2];
2208 break;
2209 case 'c':
2210 $result[0] = round(($w-$result[2])/2);
2211 break;
2212 default:
2213 $result[0] = 0;
2214 break;
2215 }
2216 switch($align[1]) {
2217 case 'b':
2218 $result[1] = $h-$result[3]; // y pos
2219 break;
2220 case 'c':
2221 $result[1] = round(($h-$result[3])/2);
2222 break;
2223 default:
2224 $result[1]=0;
2225 break;
2226 }
2227 $result = $this->applyOffset($result,t3lib_div::intExplode(',',$conf['offset']));
2228 $result = $this->applyOffset($result,$workArea);
2229 return $result;
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 * Scaling, Dimensions of images
2255 *
2256 ***********************************/
2257
2258 /**
2259 * Converts $imagefile to another file in temp-dir of type $newExt (extension).
2260 *
2261 * @param string The image filepath
2262 * @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.
2263 * @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
2264 * @param string Height. See $w
2265 * @param string Additional ImageMagick parameters.
2266 * @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...
2267 * @param array An array with options passed to getImageScale (see this function).
2268 * @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.
2269 * @return array [0]/[1] is w/h, [2] is file extension and [3] is the filename.
2270 * @see getImageScale(), typo3/show_item.php, fileList_ext::renderImage(), tslib_cObj::getImgResource(), SC_tslib_showpic::show(), maskImageOntoImage(), copyImageOntoImage(), scale()
2271 */
2272 function imageMagickConvert($imagefile,$newExt='',$w='',$h='',$params='',$frame='',$options='',$mustCreate=0) {
2273 if ($this->NO_IMAGE_MAGICK) {
2274 // Returning file info right away
2275 return $this->getImageDimensions($imagefile);
2276 }
2277
2278 if($info=$this->getImageDimensions($imagefile)) {
2279 $newExt=strtolower(trim($newExt));
2280 if (!$newExt) { // If no extension is given the original extension is used
2281 $newExt = $info[2];
2282 }
2283 if ($newExt=='web') {
2284 if (t3lib_div::inList($this->webImageExt,$info[2])) {
2285 $newExt = $info[2];
2286 } else {
2287 $newExt = $this->gif_or_jpg($info[2],$info[0],$info[1]);
2288 if (!$params) {
2289 $params = $this->cmds[$newExt];
2290 }
2291 }
2292 }
2293 if (t3lib_div::inList($this->imageFileExt,$newExt)) {
2294 if (strstr($w.$h, 'm')) {$max=1;} else {$max=0;}
2295
2296 $data = $this->getImageScale($info,$w,$h,$options);
2297 $w=$data['origW'];
2298 $h=$data['origH'];
2299
2300 // if no convertion should be performed
2301 $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....
2302
2303 if ($wh_noscale && !$data['crs'] && !$params && !$frame && $newExt==$info[2] && !$mustCreate) {
2304 $info[3] = $imagefile;
2305 return $info;
2306 }
2307 $info[0]=$data[0];
2308 $info[1]=$data[1];
2309
2310 $frame = $this->noFramePrepended ? '' : '['.intval($frame).']';
2311
2312 if (!$params) {
2313 $params = $this->cmds[$newExt];
2314 }
2315
2316 // Cropscaling:
2317 if ($data['crs']) {
2318 if (!$data['origW']) { $data['origW'] = $data[0]; }
2319 if (!$data['origH']) { $data['origH'] = $data[1]; }
2320 $offsetX = intval(($data[0] - $data['origW']) * ($data['cropH']+100)/200);
2321 $offsetY = intval(($data[1] - $data['origH']) * ($data['cropV']+100)/200);
2322 $params .= ' -crop '.$data['origW'].'x'.$data['origH'].'+'.$offsetX.'+'.$offsetY.' ';
2323 }
2324
2325 $command = $this->scalecmd.' '.$info[0].'x'.$info[1].'! '.$params.' ';
2326 $cropscale = ($data['crs'] ? 'crs-V'.$data['cropV'].'H'.$data['cropH'] : '');
2327
2328 if ($this->alternativeOutputKey) {
2329 $theOutputName = t3lib_div::shortMD5($command.$cropscale.basename($imagefile).$this->alternativeOutputKey.$frame);
2330 } else {
2331 $theOutputName = t3lib_div::shortMD5($command.$cropscale.$imagefile.filemtime($imagefile).$frame);
2332 }
2333 if ($this->imageMagickConvert_forceFileNameBody) {
2334 $theOutputName = $this->imageMagickConvert_forceFileNameBody;
2335 $this->imageMagickConvert_forceFileNameBody='';
2336 }
2337
2338 // Making the temporary filename:
2339 $this->createTempSubDir('pics/');
2340 $output = $this->absPrefix.$this->tempPath.'pics/'.$this->filenamePrefix.$theOutputName.'.'.$newExt;
2341
2342 // Register temporary filename:
2343 $GLOBALS['TEMP_IMAGES_ON_PAGE'][] = $output;
2344
2345 if ($this->dontCheckForExistingTempFile || !$this->file_exists_typo3temp_file($output, $imagefile)) {
2346 $this->imageMagickExec($imagefile.$frame, $output, $command);
2347 }
2348 if (file_exists($output)) {
2349 $info[3] = $output;
2350 $info[2] = $newExt;
2351 if ($params) { // params could realisticly change some imagedata!
2352 $info=$this->getImageDimensions($info[3]);
2353 }
2354 if ($info[2]==$this->gifExtension && !$this->dontCompress) {
2355 t3lib_div::gif_compress($info[3],''); // Compress with IM (lzw) or GD (rle) (Workaround for the absence of lzw-compression in GD)
2356 }
2357 return $info;
2358 }
2359 }
2360 }
2361 }
2362
2363 /**
2364 * Gets the input image dimensions.
2365 *
2366 * @param string The image filepath
2367 * @return array Returns an array where [0]/[1] is w/h, [2] is extension and [3] is the filename.
2368 * @see imageMagickConvert(), tslib_cObj::getImgResource()
2369 */
2370 function getImageDimensions($imageFile) {
2371 preg_match('/([^\.]*)$/',$imageFile,$reg);
2372 if (file_exists($imageFile) && t3lib_div::inList($this->imageFileExt,strtolower($reg[0]))) {
2373 if ($returnArr = $this->getCachedImageDimensions($imageFile)) {
2374 return $returnArr;
2375 } else {
2376 if ($temp = @getImageSize($imageFile)) {
2377 $returnArr = Array($temp[0], $temp[1], strtolower($reg[0]), $imageFile);
2378 } else {
2379 $returnArr = $this->imageMagickIdentify($imageFile);
2380 }
2381 if ($returnArr) {
2382 $this->cacheImageDimensions($returnArr);
2383 return $returnArr;
2384 }
2385 }
2386 }
2387 return false;
2388 }
2389
2390 /**
2391 * Cache the result of the getImageDimensions function into the database. Does not check if the
2392 * file exists!
2393 *
2394 * @param array $identifyResult: Result of the getImageDimensions function
2395 * @return boolean True if operation was successful
2396 * @author Michael Stucki <michael@typo3.org> / Robert Lemke <rl@robertlemke.de>
2397 */
2398 function cacheImageDimensions($identifyResult) {
2399 global $TYPO3_DB;
2400 // Create a md5 hash of the filename
2401 $md5Hash = md5_file($identifyResult[3]);
2402 if ($md5Hash) {
2403 $fieldArr = array (
2404 'md5hash' => $md5Hash,
2405 'md5filename' => md5($identifyResult[3]),
2406 'tstamp' => $GLOBALS['EXEC_TIME'],
2407 'filename' => $identifyResult[3],
2408 'imagewidth' => $identifyResult[0],
2409 'imageheight' => $identifyResult[1],
2410 );
2411 $TYPO3_DB->exec_INSERTquery('cache_imagesizes', $fieldArr);
2412 if (!$err = $TYPO3_DB->sql_error()) {
2413 return true;
2414 }
2415 }
2416 return false;
2417 }
2418
2419 /**
2420 * Fetch the cached imageDimensions from the MySQL database. Does not check if the image file exists!
2421 *
2422 * @param string The image filepath
2423 * @return array Returns an array where [0]/[1] is w/h, [2] is extension and [3] is the filename.
2424 * @author Michael Stucki <michael@typo3.org> / Robert Lemke <rl@robertlemke.de>
2425 */
2426 function getCachedImageDimensions($imageFile) {
2427 global $TYPO3_DB;
2428 // Create a md5 hash of the filename
2429 $md5Hash = md5_file($imageFile);
2430 preg_match('/([^\.]*)$/',$imageFile,$reg);
2431 $res = $TYPO3_DB->exec_SELECTquery ('md5hash, imagewidth, imageheight', 'cache_imagesizes', 'md5filename='.$TYPO3_DB->fullQuoteStr(md5($imageFile),'cache_imagesizes'));
2432 if ($res) {
2433 if ($row = $TYPO3_DB->sql_fetch_assoc($res)) {
2434 if ($row['md5hash']!=$md5Hash) {
2435 // file has changed, delete the row
2436 $TYPO3_DB->exec_DELETEquery ('cache_imagesizes', 'md5hash='.$TYPO3_DB->fullQuoteStr($row['md5hash'],'cache_imagesizes'));
2437 } else {
2438 return (array($row['imagewidth'], $row['imageheight'], strtolower($reg[0]), $imageFile));
2439 }
2440 }
2441 }
2442 return false;
2443 }
2444
2445 /**
2446 * Get numbers for scaling the image based on input
2447 *
2448 * @param array Current image information: Width, Height etc.
2449 * @param integer "required" width
2450 * @param integer "required" height
2451 * @param array Options: Keys are like "maxW", "maxH", "minW", "minH"
2452 * @return array
2453 * @access private
2454 * @see imageMagickConvert()
2455 */
2456 function getImageScale($info,$w,$h,$options) {
2457 if (strstr($w.$h, 'm')) {$max=1;} else {$max=0;}
2458
2459 if (strstr($w.$h, 'c')) {
2460 $out['cropH'] = intval(substr(strstr($w, 'c'), 1));
2461 $out['cropV'] = intval(substr(strstr($h, 'c'), 1));
2462 $crs = true;
2463 } else {
2464 $crs = false;
2465 }
2466 $out['crs'] = $crs;
2467
2468 $w=intval($w);
2469 $h=intval($h);
2470 // if there are max-values...
2471 if ($options['maxW']) {
2472 if ($w) { // if width is given...
2473 if ($w>$options['maxW']) {
2474 $w=$options['maxW'];
2475 $max=1; // height should follow
2476 }
2477 } else {
2478 if ($info[0]>$options['maxW']) {
2479 $w=$options['maxW'];
2480 $max=1; // height should follow
2481 }
2482 }
2483 }
2484 if ($options['maxH']) {
2485 if ($h) { // if height is given...
2486 if ($h>$options['maxH']) {
2487 $h=$options['maxH'];
2488 $max=1; // height should follow
2489 }
2490 } else {
2491 if ($info[1]>$options['maxH']) { // Changed [0] to [1] 290801
2492 $h=$options['maxH'];
2493 $max=1; // height should follow
2494 }
2495 }
2496 }
2497 $out['origW']=$w;
2498 $out['origH']=$h;
2499 $out['max'] = $max;
2500
2501 if (!$this->mayScaleUp) {
2502 if ($w>$info[0]){$w=$info[0];}
2503 if ($h>$info[1]){$h=$info[1];}
2504 }
2505 if ($w || $h) { // if scaling should be performed
2506 if ($w && !$h) {
2507 $info[1] = ceil($info[1]*($w/$info[0]));
2508 $info[0] = $w;
2509 }
2510 if (!$w && $h) {
2511 $info[0] = ceil($info[0]*($h/$info[1]));
2512 $info[1] = $h;
2513 }
2514 if ($w && $h) {
2515 if ($max) {
2516 $ratio = $info[0]/$info[1];
2517 if ($h*$ratio > $w) {
2518 $h = round($w/$ratio);
2519 } else {
2520 $w = round($h*$ratio);
2521 }
2522 }
2523 if ($crs) {
2524 $ratio = $info[0] / $info[1];
2525 if ($h * $ratio < $w) {
2526 $h = round($w / $ratio);
2527 } else {
2528 $w = round($h * $ratio);
2529 }
2530 }
2531 $info[0] = $w;
2532 $info[1] = $h;
2533 }
2534 }
2535 $out[0]=$info[0];
2536 $out[1]=$info[1];
2537 // Set minimum-measures!
2538 if ($options['minW'] && $out[0]<$options['minW']) {
2539 if (($max || $crs) && $out[0]) {
2540 $out[1]= round($out[1]*$options['minW']/$out[0]);
2541 }
2542 $out[0]=$options['minW'];
2543 }
2544 if ($options['minH'] && $out[1]<$options['minH']) {
2545 if (($max || $crs) && $out[1]) {
2546 $out[0]= round($out[0]*$options['minH']/$out[1]);
2547 }
2548 $out[1]=$options['minH'];
2549 }
2550
2551 return $out;
2552 }
2553
2554 /**
2555 * Used to check if a certain process of scaling an image is already being carried out (can be logged in the SQL database)
2556 *
2557 * @param string Output imagefile
2558 * @param string Original basis file
2559 * @return boolean Returns true if the file is already being made; thus "true" means "Don't render the image again"
2560 * @access private
2561 */
2562 function file_exists_typo3temp_file($output,$orig='') {
2563 if ($this->enable_typo3temp_db_tracking) {
2564 if (file_exists($output)) { // If file exists, then we return immediately
2565 return 1;
2566 } else { // If not, we look up in the cache_typo3temp_log table to see if there is a image being rendered right now.
2567 $md5Hash=md5($output);
2568 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
2569 'md5hash',
2570 'cache_typo3temp_log',
2571 'md5hash=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($md5Hash, 'cache_typo3temp_log') . ' AND tstamp>' . ($GLOBALS['EXEC_TIME'] - 30)
2572 );
2573 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) { // If there was a record, the image is being generated by another proces (we assume)
2574 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...)
2575 if (is_object($GLOBALS['TT'])) $GLOBALS['TT']->setTSlogMessage('typo3temp_log: Assume this file is being rendered now: '.$output);
2576 return 2; // Return 'success - 2'
2577 } 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.
2578
2579 $insertFields = array(
2580 'md5hash' => $md5Hash,
2581 'tstamp' => $GLOBALS['EXEC_TIME'],
2582 'filename' => $output,
2583 'orig_filename' => $orig
2584 );
2585 $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_typo3temp_log', 'md5hash='.$GLOBALS['TYPO3_DB']->fullQuoteStr($md5Hash, 'cache_typo3temp_log'));
2586 $GLOBALS['TYPO3_DB']->exec_INSERTquery('cache_typo3temp_log', $insertFields);
2587
2588 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);
2589 return 0;
2590 }
2591 }
2592 } else {
2593 return file_exists($output);
2594 }
2595 }
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614 /***********************************
2615 *
2616 * ImageMagick API functions
2617 *
2618 ***********************************/
2619
2620 /**
2621 * Returns an array where [0]/[1] is w/h, [2] is extension and [3] is the filename.
2622 * Using ImageMagick
2623 *
2624 * @param string The relative (to PATH_site) image filepath
2625 * @return array
2626 */
2627 function imageMagickIdentify($imagefile) {
2628 if (!$this->NO_IMAGE_MAGICK) {
2629 $frame = $this->noFramePrepended?'':'[0]';
2630 $cmd = t3lib_div::imageMagickCommand('identify', $this->wrapFileName($imagefile).$frame);
2631 $returnVal = array();
2632 exec($cmd, $returnVal);
2633 $splitstring=$returnVal[0];
2634 $this->IM_commands[] = Array ('identify',$cmd,$returnVal[0]);
2635 if ($splitstring) {
2636 preg_match('/([^\.]*)$/',$imagefile,$reg);
2637 $splitinfo = explode(' ', $splitstring);
2638 while (list($key,$val) = each($splitinfo)) {
2639 $temp = '';
2640 if ($val) {$temp = explode('x', $val);}
2641 if (intval($temp[0]) && intval($temp[1])) {
2642 $dim=$temp;
2643 break;
2644 }
2645 }
2646 if ($dim[0] && $dim[1]) {
2647 return Array($dim[0], $dim[1], strtolower($reg[0]), $imagefile);
2648 }
2649 }
2650 }
2651 }
2652
2653 /**
2654 * Executes a ImageMagick "convert" on two filenames, $input and $output using $params before them.
2655 * Can be used for many things, mostly scaling and effects.
2656 *
2657 * @param string The relative (to PATH_site) image filepath, input file (read from)
2658 * @param string The relative (to PATH_site) image filepath, output filename (written to)
2659 * @param string ImageMagick parameters
2660 * @return string The result of a call to PHP function "exec()"
2661 */
2662 function imageMagickExec($input,$output,$params) {
2663 if (!$this->NO_IMAGE_MAGICK) {
2664 $cmd = t3lib_div::imageMagickCommand('convert', $params.' '.$this->wrapFileName($input).' '.$this->wrapFileName($output));
2665 $this->IM_commands[] = array($output,$cmd);
2666
2667 $ret = exec($cmd);
2668 t3lib_div::fixPermissions($this->wrapFileName($output)); // Change the permissions of the file
2669
2670 return $ret;
2671 }
2672 }
2673
2674 /**
2675 * 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)
2676 * Can be used for many things, mostly scaling and effects.
2677 *
2678 * @param string The relative (to PATH_site) image filepath, bottom file
2679 * @param string The relative (to PATH_site) image filepath, overlay file (top)
2680 * @param string The relative (to PATH_site) image filepath, the mask file (grayscale)
2681 * @param string The relative (to PATH_site) image filepath, output filename (written to)
2682 * @param [type] $handleNegation: ...
2683 * @return void
2684 */
2685 function combineExec($input,$overlay,$mask,$output, $handleNegation = false) {
2686 if (!$this->NO_IMAGE_MAGICK) {
2687 $params = '-colorspace GRAY +matte';
2688 if ($handleNegation) {
2689 if ($this->maskNegate) {
2690 $params .= ' '.$this->maskNegate;
2691 }
2692 }
2693 $theMask = $this->randomName().'.'.$this->gifExtension;
2694 $this->imageMagickExec($mask, $theMask, $params);
2695 $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
2696 $this->IM_commands[] = Array ($output,$cmd);
2697
2698 $ret = exec($cmd);
2699 t3lib_div::fixPermissions($this->wrapFileName($output)); // Change the permissions of the file
2700
2701 if (is_file($theMask)) {
2702 @unlink($theMask);
2703 }
2704
2705 return $ret;
2706 }
2707 }
2708
2709 /**
2710 * Wrapping the input filename in double-quotes
2711 *
2712 * @param string Input filename
2713 * @return string The output wrapped in "" (if there are spaces in the filepath)
2714 * @access private
2715 */
2716 function wrapFileName($inputName) {
2717 if (strstr($inputName,' ')) {
2718 $inputName='"'.$inputName.'"';
2719 }
2720 return $inputName;
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 * Various IO functions
2748 *
2749 ***********************************/
2750
2751 /**
2752 * Returns true if the input file existed
2753 *
2754 * @param string Input file to check
2755 * @return string Returns the filename if the file existed, otherwise empty.
2756 */
2757 function checkFile($file) {
2758 if (@is_file($file)) {
2759 return $file;
2760 } else {
2761 return '';
2762 }
2763 }
2764
2765 /**
2766 * Creates subdirectory in typo3temp/ if not already found.
2767 *
2768 * @param string Name of sub directory
2769 * @return boolean Result of t3lib_div::mkdir(), true if it went well.
2770 */
2771 function createTempSubDir($dirName) {
2772
2773 // Checking if the this->tempPath is already prefixed with PATH_site and if not, prefix it with that constant.
2774 if (t3lib_div::isFirstPartOfStr($this->tempPath,PATH_site)) {
2775 $tmpPath = $this->tempPath;
2776 } else {
2777 $tmpPath = PATH_site.$this->tempPath;
2778 }
2779
2780 // Making the temporary filename:
2781 if (!@is_dir($tmpPath.$dirName)) {
2782 return t3lib_div::mkdir($tmpPath.$dirName);
2783 }
2784 }
2785
2786 /**
2787 * 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.
2788 *
2789 * @param pointer The image pointer (reference)
2790 * @param string The ImageMagick parameters. Like effects, scaling etc.
2791 * @return void
2792 */
2793 function applyImageMagickToPHPGif(&$im, $command) {
2794 $tmpStr = $this->randomName();
2795 $theFile = $tmpStr.'.'.$this->gifExtension;
2796 $this->ImageWrite($im, $theFile);
2797 $this->imageMagickExec($theFile,$theFile,$command);
2798 $tmpImg = $this->imageCreateFromFile($theFile);
2799 if ($tmpImg) {
2800 ImageDestroy($im);
2801 $im = $tmpImg;
2802 $this->w = imagesx($im);
2803 $this->h = imagesy($im);
2804 }
2805 if (!$this->dontUnlinkTempFiles) {
2806 unlink($theFile);
2807 }
2808 }
2809
2810 /**
2811 * 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.
2812 * For example: If the number of pixels exceeds $this->pixelLimitGif (normally 10000) then it will be a "jpg" string in return.
2813 *
2814 * @param string The file extension, lowercase.
2815 * @param integer The width of the output image.
2816 * @param integer The height of the output image.
2817 * @return string The filename, either "jpg" or "gif"/"png" (whatever $this->gifExtension is set to.)
2818 */
2819 function gif_or_jpg($type,$w,$h) {
2820 if ($type=='ai' || $w*$h < $this->pixelLimitGif) {
2821 return $this->gifExtension;
2822 } else {
2823 return 'jpg';
2824 }
2825 }
2826
2827 /**
2828 * Writing the internal image pointer, $this->im, to file based on the extension of the input filename
2829 * Used in GIFBUILDER
2830 * Uses $this->setup['reduceColors'] for gif/png images and $this->setup['quality'] for jpg images to reduce size/quality if needed.
2831 *
2832 * @param string The filename to write to.
2833 * @return string Returns input filename
2834 * @see tslib_gifBuilder::gifBuild()
2835 */
2836 function output($file) {
2837 if ($file) {
2838 $reg = array();
2839 preg_match('/([^\.]*)$/',$file,$reg);
2840 $ext=strtolower($reg[0]);
2841 switch($ext) {
2842 case 'gif':
2843 case 'png':
2844 if ($this->ImageWrite($this->im, $file)) {
2845 // ImageMagick operations
2846 if ($this->setup['reduceColors'] || (!$this->png_truecolor && $this->truecolor)) {
2847 $reduced = $this->IMreduceColors($file, t3lib_div::intInRange($this->setup['reduceColors'], 256, $this->truecolorColors, 256));
2848 if ($reduced) {
2849 @copy($reduced, $file);
2850 @unlink($reduced);
2851 }
2852 }
2853 t3lib_div::gif_compress($file, 'IM'); // Compress with IM! (adds extra compression, LZW from ImageMagick) (Workaround for the absence of lzw-compression in GD)
2854 }
2855 break;
2856 case 'jpg':
2857 case 'jpeg':
2858 $quality = 0; // Use the default
2859 if($this->setup['quality']) {
2860 $quality = t3lib_div::intInRange($this->setup['quality'],10,100);
2861 }
2862 if ($this->ImageWrite($this->im, $file, $quality));
2863 break;
2864 }
2865 $GLOBALS['TEMP_IMAGES_ON_PAGE'][]=$file;
2866 }
2867 return $file;
2868 }
2869
2870 /**
2871 * Destroy internal image pointer, $this->im
2872 *
2873 * @return void
2874 * @see tslib_gifBuilder::gifBuild()
2875 */
2876 function destroy() {
2877 ImageDestroy($this->im);
2878 }
2879
2880 /**
2881 * Returns Image Tag for input image information array.
2882 *
2883 * @param array Image information array, key 0/1 is width/height and key 3 is the src value
2884 * @return string Image tag for the input image information array.
2885 */
2886 function imgTag ($imgInfo) {
2887 return '<img src="'.$imgInfo[3].'" width="'.$imgInfo[0].'" height="'.$imgInfo[1].'" border="0" alt="" />';
2888 }
2889
2890 /**
2891 * Writes the input GDlib image pointer to file
2892 *
2893 * @param pointer The GDlib image resource pointer
2894 * @param string The filename to write to
2895 * @param integer The image quality (for JPEGs)
2896 * @return boolean The output of either imageGif, imagePng or imageJpeg based on the filename to write
2897 * @see maskImageOntoImage(), scale(), output()
2898 */
2899 function ImageWrite($destImg, $theImage, $quality=0) {
2900 imageinterlace ($destImg,0);
2901 $ext = strtolower(substr($theImage, strrpos($theImage, '.')+1));
2902 $result = FALSE;
2903 switch ($ext) {
2904 case 'jpg':
2905 case 'jpeg':
2906 if (function_exists('imageJpeg')) {
2907 if ($quality == 0) {
2908 $quality = $this->jpegQuality;
2909 }
2910 $result = imageJpeg($destImg, $theImage, $quality);
2911 }
2912 break;
2913 case 'gif':
2914 if (function_exists('imageGif')) {
2915 if ($this->truecolor) {
2916 imagetruecolortopalette($destImg, true, 256);
2917 }
2918 $result = imageGif($destImg, $theImage);
2919 }
2920 break;
2921 case 'png':
2922 if (function_exists('imagePng')) {
2923 $result = ImagePng($destImg, $theImage);
2924 }
2925 break;
2926 }
2927 if ($result) {
2928 t3lib_div::fixPermissions($theImage);
2929 }
2930 return $result;
2931 }
2932
2933
2934
2935 /**
2936 * Writes the input GDlib image pointer to file. Now just a wrapper to ImageWrite.
2937 *
2938 * @param pointer The GDlib image resource pointer
2939 * @param string The filename to write to
2940 * @return mixed The output of either imageGif, imagePng or imageJpeg based on the filename to write
2941 * @see imageWrite()
2942 * @deprecated since TYPO3 4.0
2943 */
2944 function imageGif($destImg, $theImage) {
2945 return $this->imageWrite($destImg, $theImage);
2946 }
2947
2948 /**
2949 * This function has been renamed and only exists for providing backwards compatibility.