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