2 /***************************************************************
5 * (c) 1999-2010 Kasper Skårhøj (kasperYYYY@typo3.com)
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.
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.
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.
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
28 * Standard graphical functions
31 * Revised for TYPO3 3.6 July/2003 by Kasper Skårhøj
33 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
36 * [CLASS/FUNCTION INDEX of SCRIPT]
40 * 155: class t3lib_stdGraphic
41 * 236: function init()
43 * SECTION: Layering images / "IMAGE" GIFBUILDER object
44 * 366: function maskImageOntoImage(&$im,$conf,$workArea)
45 * 436: function copyImageOntoImage(&$im,$conf,$workArea)
46 * 458: function copyGifOntoGif(&$im,$cpImg,$conf,$workArea)
47 * 537: function imagecopyresized(&$im, $cpImg, $Xstart, $Ystart, $cpImgCutX, $cpImgCutY, $w, $h, $w, $h)
49 * SECTION: Text / "TEXT" GIFBUILDER object
50 * 587: function makeText(&$im,$conf,$workArea)
51 * 707: function txtPosition($conf,$workArea,$BB)
52 * 761: function calcBBox($conf)
53 * 820: function addToMap($cords,$conf)
54 * 843: function calcTextCordsForMap($cords,$offset, $conf)
55 * 878: function SpacedImageTTFText(&$im, $fontSize, $angle, $x, $y, $Fcolor, $fontFile, $text, $spacing, $wordSpacing, $splitRenderingConf, $sF=1)
56 * 915: function fontResize($conf)
57 * 958: function ImageTTFBBoxWrapper($fontSize, $angle, $fontFile, $string, $splitRendering, $sF=1)
58 * 1005: function ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $color, $fontFile, $string, $splitRendering,$sF=1)
59 * 1058: function splitString($string,$splitRendering,$fontSize,$fontFile)
60 * 1208: function calcWordSpacing($conf, $scaleFactor=1)
61 * 1227: function getTextScalFactor($conf)
63 * SECTION: Other GIFBUILDER objects related to TEXT
64 * 1262: function makeOutline(&$im,$conf,$workArea,$txtConf)
65 * 1291: function circleOffset($distance, $iterations)
66 * 1315: function makeEmboss(&$im,$conf,$workArea,$txtConf)
67 * 1337: function makeShadow(&$im,$conf,$workArea,$txtConf)
69 * SECTION: Other GIFBUILDER objects
70 * 1469: function makeBox(&$im,$conf,$workArea)
71 * 1491: function makeEffect(&$im, $conf)
72 * 1506: function IMparams($setup)
73 * 1589: function adjust(&$im, $conf)
74 * 1621: function crop(&$im,$conf)
75 * 1652: function scale(&$im,$conf)
76 * 1684: function setWorkArea($workArea)
78 * SECTION: Adjustment functions
79 * 1725: function autolevels(&$im)
80 * 1756: function outputLevels(&$im,$low,$high,$swap='')
81 * 1788: function inputLevels(&$im,$low,$high,$swap='')
82 * 1819: function reduceColors(&$im,$limit, $cols)
83 * 1832: function IMreduceColors($file, $cols)
85 * SECTION: GIFBUILDER Helper functions
86 * 1875: function prependAbsolutePath($fontFile)
87 * 1889: function v5_sharpen($factor)
88 * 1908: function v5_blur($factor)
89 * 1925: function randomName()
90 * 1938: function applyOffset($cords,$OFFSET)
91 * 1951: function convertColor($string)
92 * 2001: function recodeString($string)
93 * 2023: function singleChars($theText,$returnUnicodeNumber=FALSE)
94 * 2046: function objPosition($conf,$workArea,$BB)
96 * SECTION: Scaling, Dimensions of images
97 * 2125: function imageMagickConvert($imagefile,$newExt='',$w='',$h='',$params='',$frame='',$options='',$mustCreate=0)
98 * 2238: function getImageDimensions($imageFile)
99 * 2266: function cacheImageDimensions($identifyResult)
100 * 2298: function getCachedImageDimensions($imageFile)
101 * 2332: function getImageScale($info,$w,$h,$options)
102 * 2438: function file_exists_typo3temp_file($output,$orig='')
104 * SECTION: ImageMagick API functions
105 * 2499: function imageMagickIdentify($imagefile)
106 * 2534: function imageMagickExec($input,$output,$params)
107 * 2557: function combineExec($input,$overlay,$mask,$output, $handleNegation = false)
108 * 2588: function wrapFileName($inputName)
110 * SECTION: Various IO functions
111 * 2629: function checkFile($file)
112 * 2643: function createTempSubDir($dirName)
113 * 2665: function applyImageMagickToPHPGif(&$im, $command)
114 * 2691: function gif_or_jpg($type,$w,$h)
115 * 2708: function output($file)
116 * 2748: function destroy()
117 * 2758: function imgTag ($imgInfo)
118 * 2770: function ImageWrite($destImg, $theImage)
119 * 2808: function imageGif($destImg, $theImage)
120 * 2820: function imageCreateFromGif($sourceImg)
121 * 2831: function imageCreateFromFile($sourceImg)
122 * 2870: function imagecreate($w, $h)
123 * 2885: function hexColor($col)
124 * 2903: function unifyColors(&$img, $colArr, $closest = false)
126 * TOTAL FUNCTIONS: 66
127 * (This index is automatically created/updated by the extension "extdeveval")
133 * Class contains a bunch of cool functions for manipulating graphics with GDlib/Freetype and ImageMagick
134 * VERY OFTEN used with gifbuilder that extends this class and provides a TypoScript API to using these functions
136 * With TYPO3 4.4 GDlib 1.x support was dropped, also an option from config_default.php:
137 * $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.
139 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
142 * @see tslib_gifBuilder
144 class t3lib_stdGraphic
{
146 // Internal configuration, set in init()
147 var $combineScript = 'combine'; // The ImageMagick filename used for combining two images. This name changed during the versions.
148 var $noFramePrepended = 0; // If set, there is no frame pointer prepended to the filenames.
149 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())
150 var $imagecopyresized_fix = 0; // If set, imagecopyresized will not be called directly. For GD2 (some PHP installs?)
151 var $gifExtension = 'gif'; // This should be changed to 'png' if you want this class to read/make PNG-files instead!
152 var $gdlibExtensions = ''; // File formats supported by gdlib. This variable get's filled in "init" method
153 var $truecolor = TRUE; // Internal variable which get's used to determine wheter GDlib should use function truecolor pendants, @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())
154 var $png_truecolor = FALSE; // Set to true if generated png's should be truecolor by default
155 var $truecolorColors = 0xffffff; // 16777216 Colors is the maximum value for PNG, JPEG truecolor images (24-bit, 8-bit / Channel)
156 var $TTFLocaleConv = ''; // Used to recode input to TTF-functions for other charsets. Deprecated since TYPO3 3.6, will be removed in TYPO3 4.6
157 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.
158 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!
159 var $webImageExt = 'gif,jpg,jpeg,png'; // Commalist of web image extensions (can be shown by a webbrowser)
160 var $maskNegate = ''; // Will be ' -negate' if ImageMagick ver 5.2+. See init();
161 var $NO_IM_EFFECTS = '';
166 'png' => '-colors 64'
168 var $NO_IMAGE_MAGICK = '';
170 var $im_version_4 = 0;
173 // Variables for testing, alternative usage etc.
174 var $filenamePrefix = ''; // Filename prefix for images scaled in imageMagickConvert()
175 var $imageMagickConvert_forceFileNameBody = ''; // Forcing the output filename of imageMagickConvert() to this value. However after calling imageMagickConvert() it will be set blank again.
176 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.
177 var $dontCompress = 0; // Prevents imageMagickConvert() from compressing the gif-files with t3lib_div::gif_compress()
178 var $dontUnlinkTempFiles = 0; // For debugging ONLY!
179 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...
182 var $IM_commands = array(); // All ImageMagick commands executed is stored in this array for tracking. Used by the Install Tools Image section
183 var $workArea = array();
186 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.
187 var $absPrefix = ''; // Prefix for relative paths. Used in "show_item.php" script. Is prefixed the output file name IN imageMagickConvert()
188 var $scalecmd = '-geometry'; // ImageMagick scaling command; "-geometry" eller "-sample". Used in makeText() and imageMagickConvert()
189 var $im5fx_blurSteps = '1x2,2x2,3x2,4x3,5x3,5x4,6x4,7x5,8x5,9x5'; // Used by v5_blur() to simulate 10 continuous steps of blurring
190 var $im5fx_sharpenSteps = '1x2,2x2,3x2,2x3,3x3,4x3,3x4,4x4,4x5,5x5'; // Used by v5_sharpen() to simulate 10 continuous steps of sharpening.
191 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
192 var $colMap = array( // Array mapping HTML color names to RGB values.
193 'aqua' => array(0, 255, 255),
194 'black' => array(0, 0, 0),
195 'blue' => array(0, 0, 255),
196 'fuchsia' => array(255, 0, 255),
197 'gray' => array(128, 128, 128),
198 'green' => array(0, 128, 0),
199 'lime' => array(0, 255, 0),
200 'maroon' => array(128, 0, 0),
201 'navy' => array(0, 0, 128),
202 'olive' => array(128, 128, 0),
203 'purple' => array(128, 0, 128),
204 'red' => array(255, 0, 0),
205 'silver' => array(192, 192, 192),
206 'teal' => array(0, 128, 128),
207 'yellow' => array(255, 255, 0),
208 'white' => array(255, 255, 255)
212 * Charset conversion object:
217 var $nativeCharset = ''; // Is set to the native character set of the input strings.
221 * Init function. Must always call this when using the class.
222 * This function will read the configuration information from $GLOBALS['TYPO3_CONF_VARS']['GFX'] can set some values in internal variables.
227 $gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX'];
229 if (function_exists('imagecreatefromjpeg') && function_exists('imagejpeg')) {
230 $this->gdlibExtensions
.= ',jpg,jpeg';
232 if (function_exists('imagecreatefrompng') && function_exists('imagepng')) {
233 $this->gdlibExtensions
.= ',png';
235 if (function_exists('imagecreatefromgif') && function_exists('imagegif')) {
236 $this->gdlibExtensions
.= ',gif';
238 if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['png_truecolor']) {
239 $this->png_truecolor
= true;
241 if (!$gfxConf['im_version_5']) {
242 t3lib_div
::deprecationLog('The option $TYPO3_CONF_VARS[\'GFX\'][\'im_version_5\'] is not set, ImageMagic 4 is assumed. This is deprecated since TYPO3 4.5, support will be removed in TYPO3 4.6. Make sure to upgrade to ImageMagick version 6 or GraphichsMagick.');
243 $this->im_version_4
= true;
244 } elseif ($gfxConf['im_version_5'] === 'im5') {
245 t3lib_div
::deprecationLog('The option $TYPO3_CONF_VARS[\'GFX\'][\'im_version_5\'] is set to \'im5\'. This is deprecated since TYPO3 4.5, support will be removed in TYPO3 4.6. Make sure to upgrade to ImageMagick version 6 or GraphichsMagick.');
248 // When GIFBUILDER gets used in truecolor mode
249 // No colors parameter if we generate truecolor images.
250 if ($this->png_truecolor
) {
251 $this->cmds
['png'] = '';
254 // Setting default JPG parameters:
255 $this->jpegQuality
= t3lib_div
::intInRange($gfxConf['jpg_quality'], 10, 100, 75);
256 $this->cmds
['jpg'] = $this->cmds
['jpeg'] = '-colorspace RGB -sharpen 50 -quality ' . $this->jpegQuality
;
258 if ($gfxConf['im_combine_filename']) {
259 $this->combineScript
= $gfxConf['im_combine_filename'];
261 if ($gfxConf['im_noFramePrepended']) {
262 $this->noFramePrepended
= 1;
265 // kept for backwards compatibility, can be turned on manually through localconf.php,
266 // but not through the installer anymore
267 $this->imagecopyresized_fix
= ($gfxConf['gdlib_2'] === 'no_imagecopyresized_fix' ?
0 : 1);
269 if ($gfxConf['gdlib_png']) {
270 $this->gifExtension
= 'png';
272 if ($gfxConf['TTFLocaleConv']) {
273 $this->TTFLocaleConv
= $gfxConf['TTFLocaleConv'];
275 if ($gfxConf['enable_typo3temp_db_tracking']) {
276 $this->enable_typo3temp_db_tracking
= $gfxConf['enable_typo3temp_db_tracking'];
279 $this->imageFileExt
= $gfxConf['imagefile_ext'];
281 // This should be set if ImageMagick ver. 5+ is used.
282 if ($gfxConf['im_negate_mask']) {
283 // Boolean. Indicates if the mask images should be inverted first.
284 // This depends of the ImageMagick version. Below ver. 5.1 this should be false.
285 // Above ImageMagick version 5.2+ it should be true.
286 // Just set the flag if the masks works opposite the intension!
287 $this->maskNegate
= ' -negate';
289 if ($gfxConf['im_no_effects']) {
290 // Boolean. This is necessary if using ImageMagick 5+.
291 // Effects in Imagemagick 5+ tends to render very slowly!!
292 // - therefore must be disabled in order not to perform sharpen, blurring and such.
293 $this->NO_IM_EFFECTS
= 1;
295 $this->cmds
['jpg'] = $this->cmds
['jpeg'] = '-colorspace RGB -quality ' . $this->jpegQuality
;
297 // ... but if 'im_v5effects' is set, don't care about 'im_no_effects'
298 if ($gfxConf['im_v5effects']) {
299 $this->NO_IM_EFFECTS
= 0;
300 $this->V5_EFFECTS
= 1;
302 if ($gfxConf['im_v5effects'] > 0) {
303 $this->cmds
['jpg'] = $this->cmds
['jpeg'] = '-colorspace RGB -quality ' . intval($gfxConf['jpg_quality']) . $this->v5_sharpen(10);
307 if (!$gfxConf['im']) {
308 $this->NO_IMAGE_MAGICK
= 1;
310 // Secures that images are not scaled up.
311 if ($gfxConf['im_noScaleUp']) {
312 $this->mayScaleUp
= 0;
315 if (TYPO3_MODE
== 'FE') {
316 $this->csConvObj
= $GLOBALS['TSFE']->csConvObj
;
317 } elseif (is_object($GLOBALS['LANG'])) { // BE assumed:
318 $this->csConvObj
= $GLOBALS['LANG']->csConvObj
;
319 } else { // The object may not exist yet, so we need to create it now. Happens in the Install Tool for example.
320 $this->csConvObj
= t3lib_div
::makeInstance('t3lib_cs');
322 $this->nativeCharset
= $GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'];
326 /*************************************************
328 * Layering images / "IMAGE" GIFBUILDER object
330 *************************************************/
333 * Implements the "IMAGE" GIFBUILDER object, when the "mask" property is true.
334 * 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
335 * The operation involves ImageMagick for combining.
337 * @param pointer GDlib image pointer
338 * @param array TypoScript array with configuration for the GIFBUILDER object.
339 * @param array The current working area coordinates.
341 * @see tslib_gifBuilder::make()
343 function maskImageOntoImage(&$im, $conf, $workArea) {
344 if ($conf['file'] && $conf['mask']) {
345 $imgInf = pathinfo($conf['file']);
346 $imgExt = strtolower($imgInf['extension']);
347 if (!t3lib_div
::inList($this->gdlibExtensions
, $imgExt)) {
348 $BBimage = $this->imageMagickConvert($conf['file'], $this->gifExtension
, '', '', '', '', '');
350 $BBimage = $this->getImageDimensions($conf['file']);
352 $maskInf = pathinfo($conf['mask']);
353 $maskExt = strtolower($maskInf['extension']);
354 if (!t3lib_div
::inList($this->gdlibExtensions
, $maskExt)) {
355 $BBmask = $this->imageMagickConvert($conf['mask'], $this->gifExtension
, '', '', '', '', '');
357 $BBmask = $this->getImageDimensions($conf['mask']);
359 if ($BBimage && $BBmask) {
362 $tmpStr = $this->randomName();
363 $theImage = $tmpStr . '_img.' . $this->gifExtension
;
364 $theDest = $tmpStr . '_dest.' . $this->gifExtension
;
365 $theMask = $tmpStr . '_mask.' . $this->gifExtension
;
366 // prepare overlay image
367 $cpImg = $this->imageCreateFromFile($BBimage[3]);
368 $destImg = imagecreatetruecolor($w, $h);
369 $Bcolor = ImageColorAllocate($destImg, 0, 0, 0);
370 ImageFilledRectangle($destImg, 0, 0, $w, $h, $Bcolor);
371 $this->copyGifOntoGif($destImg, $cpImg, $conf, $workArea);
372 $this->ImageWrite($destImg, $theImage);
373 imageDestroy($cpImg);
374 imageDestroy($destImg);
375 // prepare mask image
376 $cpImg = $this->imageCreateFromFile($BBmask[3]);
377 $destImg = imagecreatetruecolor($w, $h);
378 $Bcolor = ImageColorAllocate($destImg, 0, 0, 0);
379 ImageFilledRectangle($destImg, 0, 0, $w, $h, $Bcolor);
380 $this->copyGifOntoGif($destImg, $cpImg, $conf, $workArea);
381 $this->ImageWrite($destImg, $theMask);
382 imageDestroy($cpImg);
383 imageDestroy($destImg);
385 $this->ImageWrite($im, $theDest);
387 $this->combineExec($theDest, $theImage, $theMask, $theDest, TRUE); // Let combineExec handle maskNegation
389 $backIm = $this->imageCreateFromFile($theDest); // The main image is loaded again...
390 if ($backIm) { // ... and if nothing went wrong we load it onto the old one.
391 ImageColorTransparent($backIm, -1);
394 // unlink files from process
395 if (!$this->dontUnlinkTempFiles
) {
405 * Implements the "IMAGE" GIFBUILDER object, when the "mask" property is false (using only $conf['file'])
407 * @param pointer GDlib image pointer
408 * @param array TypoScript array with configuration for the GIFBUILDER object.
409 * @param array The current working area coordinates.
411 * @see tslib_gifBuilder::make(), maskImageOntoImage()
413 function copyImageOntoImage(&$im, $conf, $workArea) {
415 if (!t3lib_div
::inList($this->gdlibExtensions
, $conf['BBOX'][2])) {
416 $conf['BBOX'] = $this->imageMagickConvert($conf['BBOX'][3], $this->gifExtension
, '', '', '', '', '');
417 $conf['file'] = $conf['BBOX'][3];
419 $cpImg = $this->imageCreateFromFile($conf['file']);
420 $this->copyGifOntoGif($im, $cpImg, $conf, $workArea);
421 imageDestroy($cpImg);
426 * Copies two GDlib image pointers onto each other, using TypoScript configuration from $conf and the input $workArea definition.
428 * @param pointer GDlib image pointer, destination (bottom image)
429 * @param pointer GDlib image pointer, source (top image)
430 * @param array TypoScript array with the properties for the IMAGE GIFBUILDER object. Only used for the "tile" property value.
431 * @param array Work area
432 * @return void Works on the $im image pointer
435 function copyGifOntoGif(&$im, $cpImg, $conf, $workArea) {
436 $cpW = imagesx($cpImg);
437 $cpH = imagesy($cpImg);
438 $tile = t3lib_div
::intExplode(',', $conf['tile']);
439 $tile[0] = t3lib_div
::intInRange($tile[0], 1, 20);
440 $tile[1] = t3lib_div
::intInRange($tile[1], 1, 20);
441 $cpOff = $this->objPosition($conf, $workArea, array($cpW * $tile[0], $cpH * $tile[1]));
443 for ($xt = 0; $xt < $tile[0]; $xt++
) {
444 $Xstart = $cpOff[0] +
$cpW * $xt;
445 if ($Xstart +
$cpW > $workArea[0]) { // if this image is inside of the workArea, then go on
447 if ($Xstart < $workArea[0]) {
448 $cpImgCutX = $workArea[0] - $Xstart;
449 $Xstart = $workArea[0];
453 $w = $cpW - $cpImgCutX;
454 if ($Xstart > $workArea[0] +
$workArea[2] - $w) {
455 $w = $workArea[0] +
$workArea[2] - $Xstart;
457 if ($Xstart < $workArea[0] +
$workArea[2]) { // if this image is inside of the workArea, then go on
459 for ($yt = 0; $yt < $tile[1]; $yt++
) {
460 $Ystart = $cpOff[1] +
$cpH * $yt;
461 if ($Ystart +
$cpH > $workArea[1]) { // if this image is inside of the workArea, then go on
462 if ($Ystart < $workArea[1]) {
463 $cpImgCutY = $workArea[1] - $Ystart;
464 $Ystart = $workArea[1];
468 $h = $cpH - $cpImgCutY;
469 if ($Ystart > $workArea[1] +
$workArea[3] - $h) {
470 $h = $workArea[1] +
$workArea[3] - $Ystart;
472 if ($Ystart < $workArea[1] +
$workArea[3]) { // if this image is inside of the workArea, then go on
473 $this->imagecopyresized($im, $cpImg, $Xstart, $Ystart, $cpImgCutX, $cpImgCutY, $w, $h, $w, $h);
483 * Alternative function for using the similar PHP function imagecopyresized(). Used for GD2 only.
485 * OK, the reason for this stupid fix is the following story:
486 * GD1.x was capable of copying two images together and combining their palettes! GD2 is apparently not.
487 * With GD2 only the palette of the dest-image is used which mostly results in totally black images when trying to
488 * copy a color-ful image onto the destination.
490 * 1) Create a blank TRUE-COLOR image
491 * 2) Copy the destination image onto that one
492 * 3) Then do the actual operation; Copying the source (top image) onto that
493 * 4) ... and return the result pointer.
494 * 5) Reduce colors (if we do not, the result may become strange!)
495 * It works, but the resulting images is now a true-color PNG which may be very large.
496 * So, why not use 'imagetruecolortopalette ($im, TRUE, 256)' - well because it does NOT WORK! So simple is that.
498 * For parameters, see PHP function "imagecopyresized()"
500 * @param pointer see PHP function "imagecopyresized()"
501 * @param pointer see PHP function "imagecopyresized()"
502 * @param integer see PHP function "imagecopyresized()"
503 * @param integer see PHP function "imagecopyresized()"
504 * @param integer see PHP function "imagecopyresized()"
505 * @param integer see PHP function "imagecopyresized()"
506 * @param integer see PHP function "imagecopyresized()"
507 * @param integer see PHP function "imagecopyresized()"
508 * @param integer see PHP function "imagecopyresized()"
509 * @param integer see PHP function "imagecopyresized()"
512 * @see t3lib_iconWorks::imagecopyresized()
514 function imagecopyresized(&$im, $cpImg, $Xstart, $Ystart, $cpImgCutX, $cpImgCutY, $w, $h, $w, $h) {
515 if ($this->imagecopyresized_fix
) {
516 $im_base = imagecreatetruecolor(imagesx($im), imagesy($im)); // Make true color image
517 imagecopyresized($im_base, $im, 0, 0, 0, 0, imagesx($im), imagesy($im), imagesx($im), imagesy($im)); // Copy the source image onto that
518 imagecopyresized($im_base, $cpImg, $Xstart, $Ystart, $cpImgCutX, $cpImgCutY, $w, $h, $w, $h); // Then copy the $cpImg onto that (the actual operation!)
519 $im = $im_base; // Set pointer
520 if (!$this->truecolor
) {
521 $this->makeEffect($im, array('value' => 'colors=' . t3lib_div
::intInRange($this->setup
['reduceColors'], 256, $this->truecolorColors
, 256))); // Reduce to "reduceColors" colors - make SURE that IM is working then!
524 imagecopyresized($im, $cpImg, $Xstart, $Ystart, $cpImgCutX, $cpImgCutY, $w, $h, $w, $h);
529 /********************************
531 * Text / "TEXT" GIFBUILDER object
533 ********************************/
536 * Implements the "TEXT" GIFBUILDER object
538 * @param pointer GDlib image pointer
539 * @param array TypoScript array with configuration for the GIFBUILDER object.
540 * @param array The current working area coordinates.
542 * @see tslib_gifBuilder::make()
544 function makeText(&$im, $conf, $workArea) {
546 list($spacing, $wordSpacing) = $this->calcWordSpacing($conf);
548 $txtPos = $this->txtPosition($conf, $workArea, $conf['BBOX']);
549 $theText = $this->recodeString($conf['text']);
551 if ($conf['imgMap'] && is_array($conf['imgMap.'])) {
552 $this->addToMap($this->calcTextCordsForMap($conf['BBOX'][2], $txtPos, $conf['imgMap.']), $conf['imgMap.']);
554 if (!$conf['hideButCreateMap']) {
556 $cols = $this->convertColor($conf['fontColor']);
557 // NiceText is calculated
558 if (!$conf['niceText']) {
559 // Font Color is reserved:
560 if (!$this->truecolor
) {
561 $reduce = t3lib_div
::intInRange($this->setup
['reduceColors'], 256, $this->truecolorColors
, 256);
562 $this->reduceColors($im, $reduce - 49, $reduce - 50); // If "reduce-49" colors (or more) are used reduce them to "reduce-50"
564 $Fcolor = ImageColorAllocate($im, $cols[0], $cols[1], $cols[2]);
565 // antiAliasing is setup:
566 $Fcolor = ($conf['antiAlias']) ?
$Fcolor : -$Fcolor;
568 for ($a = 0; $a < $conf['iterations']; $a++
) {
569 if ($spacing ||
$wordSpacing) { // If any kind of spacing applys, we use this function:
570 $this->SpacedImageTTFText($im, $conf['fontSize'], $conf['angle'], $txtPos[0], $txtPos[1], $Fcolor, t3lib_stdGraphic
::prependAbsolutePath($conf['fontFile']), $theText, $spacing, $wordSpacing, $conf['splitRendering.']);
572 $this->renderTTFText($im, $conf['fontSize'], $conf['angle'], $txtPos[0], $txtPos[1], $Fcolor, $conf['fontFile'], $theText, $conf['splitRendering.'], $conf);
575 } else { // NICETEXT::
576 // options anti_aliased and iterations is NOT available when doing this!!
579 $tmpStr = $this->randomName();
581 $fileMenu = $tmpStr . '_menuNT.' . $this->gifExtension
;
582 $fileColor = $tmpStr . '_colorNT.' . $this->gifExtension
;
583 $fileMask = $tmpStr . '_maskNT.' . $this->gifExtension
;
585 $sF = t3lib_div
::intInRange($conf['niceText.']['scaleFactor'], 2, 5);
586 $newW = ceil($sF * imagesx($im));
587 $newH = ceil($sF * imagesy($im));
590 $maskImg = imagecreatetruecolor($newW, $newH);
591 $Bcolor = ImageColorAllocate($maskImg, 255, 255, 255);
592 ImageFilledRectangle($maskImg, 0, 0, $newW, $newH, $Bcolor);
593 $Fcolor = ImageColorAllocate($maskImg, 0, 0, 0);
594 if ($spacing ||
$wordSpacing) { // If any kind of spacing applys, we use this function:
595 $this->SpacedImageTTFText($maskImg, $conf['fontSize'], $conf['angle'], $txtPos[0], $txtPos[1], $Fcolor, t3lib_stdGraphic
::prependAbsolutePath($conf['fontFile']), $theText, $spacing, $wordSpacing, $conf['splitRendering.'], $sF);
597 $this->renderTTFText($maskImg, $conf['fontSize'], $conf['angle'], $txtPos[0], $txtPos[1], $Fcolor, $conf['fontFile'], $theText, $conf['splitRendering.'], $conf, $sF);
599 $this->ImageWrite($maskImg, $fileMask);
600 ImageDestroy($maskImg);
602 // Downscales the mask
603 if ($this->NO_IM_EFFECTS
) {
604 if ($this->maskNegate
) {
605 $command = trim($this->scalecmd
. ' ' . $w . 'x' . $h . '!'); // Negate 2 times makes no negate...
607 $command = trim($this->scalecmd
. ' ' . $w . 'x' . $h . '! -negate');
610 if ($this->maskNegate
) {
611 $command = trim($conf['niceText.']['before'] . ' ' . $this->scalecmd
. ' ' . $w . 'x' . $h . '! ' . $conf['niceText.']['after']);
613 $command = trim($conf['niceText.']['before'] . ' ' . $this->scalecmd
. ' ' . $w . 'x' . $h . '! ' . $conf['niceText.']['after'] . ' -negate');
615 if ($conf['niceText.']['sharpen']) {
616 if ($this->V5_EFFECTS
) {
617 $command .= $this->v5_sharpen($conf['niceText.']['sharpen']);
619 $command .= ' -sharpen ' . t3lib_div
::intInRange($conf['niceText.']['sharpen'], 1, 99);
624 $this->imageMagickExec($fileMask, $fileMask, $command);
626 // Make the color-file
627 $colorImg = imagecreatetruecolor($w, $h);
628 $Ccolor = ImageColorAllocate($colorImg, $cols[0], $cols[1], $cols[2]);
629 ImageFilledRectangle($colorImg, 0, 0, $w, $h, $Ccolor);
630 $this->ImageWrite($colorImg, $fileColor);
631 ImageDestroy($colorImg);
633 // The mask is applied
634 $this->ImageWrite($im, $fileMenu); // The main pictures is saved temporarily
636 $this->combineExec($fileMenu, $fileColor, $fileMask, $fileMenu);
638 $backIm = $this->imageCreateFromFile($fileMenu); // The main image is loaded again...
639 if ($backIm) { // ... and if nothing went wrong we load it onto the old one.
640 ImageColorTransparent($backIm, -1);
644 // Deleting temporary files;
645 if (!$this->dontUnlinkTempFiles
) {
655 * Calculates text position for printing the text onto the image based on configuration like alignment and workarea.
657 * @param array TypoScript array for the TEXT GIFBUILDER object
658 * @param array Workarea definition
659 * @param array Bounding box information, was set in tslib_gifBuilder::start()
660 * @return array [0]=x, [1]=y, [2]=w, [3]=h
664 function txtPosition($conf, $workArea, $BB) {
666 $angle = intval($conf['angle']) / 180 * pi();
668 $straightBB = $this->calcBBox($conf);
670 // offset, align, valign, workarea
671 $result = array(); // [0]=x, [1]=y, [2]=w, [3]=h
677 switch ($conf['align']) {
680 $factor = abs(cos($angle));
681 $sign = (cos($angle) < 0) ?
-1 : 1;
682 $len1 = $sign * $factor * $straightBB[0];
683 $len2 = $sign * $BB[0];
684 $result[0] = $w - ceil($len2 * $factor +
(1 - $factor) * $len1);
686 $factor = abs(sin($angle));
687 $sign = (sin($angle) < 0) ?
-1 : 1;
688 $len1 = $sign * $factor * $straightBB[0];
689 $len2 = $sign * $BB[1];
690 $result[1] = ceil($len2 * $factor +
(1 - $factor) * $len1);
693 switch ($conf['align']) {
697 $result[0] = round(($result[0]) / 2);
698 $result[1] = round(($result[1]) / 2);
705 $result = $this->applyOffset($result, t3lib_div
::intExplode(',', $conf['offset']));
706 $result = $this->applyOffset($result, $workArea);
711 * Calculates bounding box information for the TEXT GIFBUILDER object.
713 * @param array TypoScript array for the TEXT GIFBUILDER object
714 * @return array Array with three keys [0]/[1] being x/y and [2] being the bounding box array
716 * @see txtPosition(), tslib_gifBuilder::start()
718 function calcBBox($conf) {
719 $sF = $this->getTextScalFactor($conf);
720 list($spacing, $wordSpacing) = $this->calcWordSpacing($conf, $sF);
721 $theText = $this->recodeString($conf['text']);
723 $charInf = $this->ImageTTFBBoxWrapper($conf['fontSize'], $conf['angle'], $conf['fontFile'], $theText, $conf['splitRendering.'], $sF);
724 $theBBoxInfo = $charInf;
725 if ($conf['angle']) {
726 $xArr = array($charInf[0], $charInf[2], $charInf[4], $charInf[6]);
727 $yArr = array($charInf[1], $charInf[3], $charInf[5], $charInf[7]);
728 $x = max($xArr) - min($xArr);
729 $y = max($yArr) - min($yArr);
731 $x = ($charInf[2] - $charInf[0]);
732 $y = ($charInf[1] - $charInf[7]);
734 // Set original lineHeight (used by line breaks):
735 $theBBoxInfo['lineHeight'] = $y;
737 if ($spacing ||
$wordSpacing) { // If any kind of spacing applys, we use this function:
739 if (!$spacing && $wordSpacing) {
740 $bits = explode(' ', $theText);
741 foreach ($bits as $word) {
743 $wordInf = $this->ImageTTFBBoxWrapper($conf['fontSize'], $conf['angle'], $conf['fontFile'], $word, $conf['splitRendering.'], $sF);
744 $wordW = ($wordInf[2] - $wordInf[0]);
745 $x +
= $wordW +
$wordSpacing;
748 $utf8Chars = $this->singleChars($theText);
749 // For each UTF-8 char, do:
750 foreach ($utf8Chars as $char) {
751 $charInf = $this->ImageTTFBBoxWrapper($conf['fontSize'], $conf['angle'], $conf['fontFile'], $char, $conf['splitRendering.'], $sF);
752 $charW = ($charInf[2] - $charInf[0]);
753 $x +
= $charW +
(($char == ' ') ?
$wordSpacing : $spacing);
756 } elseif (isset($conf['breakWidth']) && $conf['breakWidth'] && $this->getRenderedTextWidth($conf['text'], $conf) > $conf['breakWidth']) {
759 $breakWidth = $conf['breakWidth'];
760 $breakSpace = $this->getBreakSpace($conf, $theBBoxInfo);
762 $wordPairs = $this->getWordPairsForLineBreak($conf['text']);
763 // Iterate through all word pairs:
764 foreach ($wordPairs as $index => $wordPair) {
765 $wordWidth = $this->getRenderedTextWidth($wordPair, $conf);
766 if ($index == 0 ||
$currentWidth +
$wordWidth <= $breakWidth) {
767 $currentWidth +
= $wordWidth;
769 $maxWidth = max($maxWidth, $currentWidth);
772 $currentWidth = $wordWidth;
775 $x = max($maxWidth, $currentWidth) * $sF;
781 if (is_array($theBBoxInfo)) {
782 foreach ($theBBoxInfo as &$value) {
783 $value = ceil($value / $sF);
787 return array($x, $y, $theBBoxInfo);
791 * Adds an <area> tag to the internal variable $this->map which is used to accumulate the content for an ImageMap
793 * @param array Coordinates for a polygon image map as created by ->calcTextCordsForMap()
794 * @param array Configuration for "imgMap." property of a TEXT GIFBUILDER object.
797 * @see makeText(), calcTextCordsForMap()
799 function addToMap($cords, $conf) {
800 $JS = $conf['noBlur'] ?
'' : ' onfocus="blurLink(this);"';
802 $this->map
.= '<area' .
804 ' coords="' . implode(',', $cords) . '"' .
805 ' href="' . htmlspecialchars($conf['url']) . '"' .
806 ($conf['target'] ?
' target="' . htmlspecialchars($conf['target']) . '"' : '') .
808 (strlen($conf['titleText']) ?
' title="' . htmlspecialchars($conf['titleText']) . '"' : '') .
809 ' alt="' . htmlspecialchars($conf['altText']) . '" />';
813 * Calculating the coordinates for a TEXT string on an image map. Used in an <area> tag
815 * @param array Coordinates (from BBOX array)
816 * @param array Offset array
817 * @param array Configuration for "imgMap." property of a TEXT GIFBUILDER object.
820 * @see makeText(), calcTextCordsForMap()
822 function calcTextCordsForMap($cords, $offset, $conf) {
823 $pars = t3lib_div
::intExplode(',', $conf['explode'] . ',');
825 $newCords[0] = $cords[0] +
$offset[0] - $pars[0];
826 $newCords[1] = $cords[1] +
$offset[1] +
$pars[1];
827 $newCords[2] = $cords[2] +
$offset[0] +
$pars[0];
828 $newCords[3] = $cords[3] +
$offset[1] +
$pars[1];
829 $newCords[4] = $cords[4] +
$offset[0] +
$pars[0];
830 $newCords[5] = $cords[5] +
$offset[1] - $pars[1];
831 $newCords[6] = $cords[6] +
$offset[0] - $pars[0];
832 $newCords[7] = $cords[7] +
$offset[1] - $pars[1];
838 * Printing text onto an image like the PHP function imageTTFText does but in addition it offers options for spacing of letters and words.
839 * Spacing is done by printing one char at a time and this means that the spacing is rather uneven and probably not very nice.
842 * @param pointer (See argument for PHP function imageTTFtext())
843 * @param integer (See argument for PHP function imageTTFtext())
844 * @param integer (See argument for PHP function imageTTFtext())
845 * @param integer (See argument for PHP function imageTTFtext())
846 * @param integer (See argument for PHP function imageTTFtext())
847 * @param integer (See argument for PHP function imageTTFtext())
848 * @param string (See argument for PHP function imageTTFtext())
849 * @param string (See argument for PHP function imageTTFtext()). UTF-8 string, possibly with entities in.
850 * @param integer The spacing of letters in pixels
851 * @param integer The spacing of words in pixels
852 * @param array $splitRenderingConf array
853 * @param integer Scale factor
857 function SpacedImageTTFText(&$im, $fontSize, $angle, $x, $y, $Fcolor, $fontFile, $text, $spacing, $wordSpacing, $splitRenderingConf, $sF = 1) {
862 if (!$spacing && $wordSpacing) {
863 $bits = explode(' ', $text);
864 foreach ($bits as $word) {
866 $wordInf = $this->ImageTTFBBoxWrapper($fontSize, $angle, $fontFile, $word, $splitRenderingConf, $sF);
867 $wordW = ($wordInf[2] - $wordInf[0]);
868 $this->ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $Fcolor, $fontFile, $word, $splitRenderingConf, $sF);
869 $x +
= $wordW +
$wordSpacing;
872 $utf8Chars = $this->singleChars($text);
873 // For each UTF-8 char, do:
874 foreach ($utf8Chars as $char) {
875 $charInf = $this->ImageTTFBBoxWrapper($fontSize, $angle, $fontFile, $char, $splitRenderingConf, $sF);
876 $charW = ($charInf[2] - $charInf[0]);
877 $this->ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $Fcolor, $fontFile, $char, $splitRenderingConf, $sF);
878 $x +
= $charW +
(($char == ' ') ?
$wordSpacing : $spacing);
884 * Function that finds the right fontsize that will render the textstring within a certain width
886 * @param array The TypoScript properties of the TEXT GIFBUILDER object
887 * @return integer The new fontSize
889 * @author René Fritz <r.fritz@colorcube.de>
890 * @see tslib_gifBuilder::start()
892 function fontResize($conf) {
893 // 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!!!!
894 $maxWidth = intval($conf['maxWidth']);
895 list($spacing, $wordSpacing) = $this->calcWordSpacing($conf);
897 if ($spacing ||
$wordSpacing) { // If any kind of spacing applys, we use this function:
898 return $conf['fontSize'];
899 // ################ no calc for spacing yet !!!!!!
902 // determine bounding box.
903 $bounds = $this->ImageTTFBBoxWrapper($conf['fontSize'], $conf['angle'], $conf['fontFile'], $this->recodeString($conf['text']), $conf['splitRendering.']);
904 if ($conf['angle'] < 0) {
905 $pixelWidth = abs($bounds[4] - $bounds[0]);
906 } elseif ($conf['angle'] > 0) {
907 $pixelWidth = abs($bounds[2] - $bounds[6]);
909 $pixelWidth = abs($bounds[4] - $bounds[6]);
912 // Size is fine, exit:
913 if ($pixelWidth <= $maxWidth) {
918 } while ($conf['fontSize'] > 1);
922 return $conf['fontSize'];
926 * Wrapper for ImageTTFBBox
928 * @param integer (See argument for PHP function ImageTTFBBox())
929 * @param integer (See argument for PHP function ImageTTFBBox())
930 * @param string (See argument for PHP function ImageTTFBBox())
931 * @param string (See argument for PHP function ImageTTFBBox())
932 * @param array Split-rendering configuration
933 * @param integer Scale factor
934 * @return array Information array.
936 function ImageTTFBBoxWrapper($fontSize, $angle, $fontFile, $string, $splitRendering, $sF = 1) {
939 $offsetInfo = array();
940 $stringParts = $this->splitString($string, $splitRendering, $fontSize, $fontFile);
942 // Traverse string parts:
943 foreach ($stringParts as $strCfg) {
944 $fontFile = t3lib_stdGraphic
::prependAbsolutePath($strCfg['fontFile']);
945 if (is_readable($fontFile)) {
947 // Calculate Bounding Box for part:
948 $calc = ImageTTFBBox(t3lib_div
::freetypeDpiComp($sF * $strCfg['fontSize']), $angle, $fontFile, $strCfg['str']);
950 // Calculate offsets:
951 if (!count($offsetInfo)) {
952 $offsetInfo = $calc; // First run, just copy over.
954 $offsetInfo[2] +
= $calc[2] - $calc[0] +
intval($splitRendering['compX']) +
intval($strCfg['xSpaceBefore']) +
intval($strCfg['xSpaceAfter']);
955 $offsetInfo[3] +
= $calc[3] - $calc[1] - intval($splitRendering['compY']) - intval($strCfg['ySpaceBefore']) - intval($strCfg['ySpaceAfter']);
956 $offsetInfo[4] +
= $calc[4] - $calc[6] +
intval($splitRendering['compX']) +
intval($strCfg['xSpaceBefore']) +
intval($strCfg['xSpaceAfter']);
957 $offsetInfo[5] +
= $calc[5] - $calc[7] - intval($splitRendering['compY']) - intval($strCfg['ySpaceBefore']) - intval($strCfg['ySpaceAfter']);
961 debug('cannot read file: ' . $fontFile, 't3lib_stdGraphic::ImageTTFBBoxWrapper()');
969 * Wrapper for ImageTTFText
971 * @param pointer (See argument for PHP function imageTTFtext())
972 * @param integer (See argument for PHP function imageTTFtext())
973 * @param integer (See argument for PHP function imageTTFtext())
974 * @param integer (See argument for PHP function imageTTFtext())
975 * @param integer (See argument for PHP function imageTTFtext())
976 * @param integer (See argument for PHP function imageTTFtext())
977 * @param string (See argument for PHP function imageTTFtext())
978 * @param string (See argument for PHP function imageTTFtext()). UTF-8 string, possibly with entities in.
979 * @param array Split-rendering configuration
980 * @param integer Scale factor
983 function ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $color, $fontFile, $string, $splitRendering, $sF = 1) {
986 $stringParts = $this->splitString($string, $splitRendering, $fontSize, $fontFile);
990 // Traverse string parts:
991 foreach ($stringParts as $i => $strCfg) {
994 $colorIndex = $color;
996 // Set custom color if any (only when niceText is off):
997 if ($strCfg['color'] && $sF == 1) {
998 $cols = $this->convertColor($strCfg['color']);
999 $colorIndex = ImageColorAllocate($im, $cols[0], $cols[1], $cols[2]);
1000 $colorIndex = $color >= 0 ?
$colorIndex : -$colorIndex;
1003 // Setting xSpaceBefore
1005 $x +
= intval($strCfg['xSpaceBefore']);
1006 $y -= intval($strCfg['ySpaceBefore']);
1009 $fontFile = t3lib_stdGraphic
::prependAbsolutePath($strCfg['fontFile']);
1010 if (is_readable($fontFile)) {
1013 ImageTTFText($im, t3lib_div
::freetypeDpiComp($sF * $strCfg['fontSize']), $angle, $x, $y, $colorIndex, $fontFile, $strCfg['str']);
1015 // Calculate offset to apply:
1016 $wordInf = ImageTTFBBox(t3lib_div
::freetypeDpiComp($sF * $strCfg['fontSize']), $angle, t3lib_stdGraphic
::prependAbsolutePath($strCfg['fontFile']), $strCfg['str']);
1017 $x +
= $wordInf[2] - $wordInf[0] +
intval($splitRendering['compX']) +
intval($strCfg['xSpaceAfter']);
1018 $y +
= $wordInf[5] - $wordInf[7] - intval($splitRendering['compY']) - intval($strCfg['ySpaceAfter']);
1021 debug('cannot read file: ' . $fontFile, 't3lib_stdGraphic::ImageTTFTextWrapper()');
1028 * Splitting a string for ImageTTFBBox up into an array where each part has its own configuration options.
1030 * @param string UTF-8 string
1031 * @param array Split-rendering configuration from GIFBUILDER TEXT object.
1032 * @param integer Current fontsize
1033 * @param string Current font file
1034 * @return array Array with input string splitted according to configuration
1036 function splitString($string, $splitRendering, $fontSize, $fontFile) {
1038 // Initialize by setting the whole string and default configuration as the first entry.
1042 'fontSize' => $fontSize,
1043 'fontFile' => $fontFile
1046 // Traverse the split-rendering configuration:
1047 // Splitting will create more entries in $result with individual configurations.
1048 if (is_array($splitRendering)) {
1049 $sKeyArray = t3lib_TStemplate
::sortedKeyList($splitRendering);
1051 // Traverse configured options:
1052 foreach ($sKeyArray as $key) {
1053 $cfg = $splitRendering[$key . '.'];
1055 // Process each type of split rendering keyword:
1056 switch ((string) $splitRendering[$key]) {
1057 case 'highlightWord':
1058 if (strlen($cfg['value'])) {
1059 $newResult = array();
1061 // Traverse the current parts of the result array:
1062 foreach ($result as $part) {
1063 // Explode the string value by the word value to highlight:
1064 $explodedParts = explode($cfg['value'], $part['str']);
1065 foreach ($explodedParts as $c => $expValue) {
1066 if (strlen($expValue)) {
1067 $newResult[] = array_merge($part, array('str' => $expValue));
1069 if ($c +
1 < count($explodedParts)) {
1070 $newResult[] = array(
1071 'str' => $cfg['value'],
1072 'fontSize' => $cfg['fontSize'] ?
$cfg['fontSize'] : $part['fontSize'],
1073 'fontFile' => $cfg['fontFile'] ?
$cfg['fontFile'] : $part['fontFile'],
1074 'color' => $cfg['color'],
1075 'xSpaceBefore' => $cfg['xSpaceBefore'],
1076 'xSpaceAfter' => $cfg['xSpaceAfter'],
1077 'ySpaceBefore' => $cfg['ySpaceBefore'],
1078 'ySpaceAfter' => $cfg['ySpaceAfter'],
1084 // Set the new result as result array:
1085 if (count($newResult)) {
1086 $result = $newResult;
1091 if (strlen($cfg['value'])) {
1093 // Initialize range:
1094 $ranges = t3lib_div
::trimExplode(',', $cfg['value'], 1);
1095 foreach ($ranges as $i => $rangeDef) {
1096 $ranges[$i] = t3lib_div
::intExplode('-', $ranges[$i]);
1097 if (!isset($ranges[$i][1])) {
1098 $ranges[$i][1] = $ranges[$i][0];
1101 $newResult = array();
1103 // Traverse the current parts of the result array:
1104 foreach ($result as $part) {
1110 // Explode the string value by the word value to highlight:
1111 $utf8Chars = $this->singleChars($part['str']);
1112 foreach ($utf8Chars as $utfChar) {
1114 // Find number and evaluate position:
1115 $uNumber = $this->csConvObj
->utf8CharToUnumber($utfChar);
1117 foreach ($ranges as $rangeDef) {
1118 if ($uNumber >= $rangeDef[0] && (!$rangeDef[1] ||
$uNumber <= $rangeDef[1])) {
1123 if ($currentState == -1) {
1124 $currentState = $inRange;
1125 } // Initialize first char
1128 if ($inRange != $currentState && !t3lib_div
::inList('32,10,13,9', $uNumber)) {
1131 if (strlen($bankAccum)) {
1132 $newResult[] = array(
1133 'str' => $bankAccum,
1134 'fontSize' => $currentState && $cfg['fontSize'] ?
$cfg['fontSize'] : $part['fontSize'],
1135 'fontFile' => $currentState && $cfg['fontFile'] ?
$cfg['fontFile'] : $part['fontFile'],
1136 'color' => $currentState ?
$cfg['color'] : '',
1137 'xSpaceBefore' => $currentState ?
$cfg['xSpaceBefore'] : '',
1138 'xSpaceAfter' => $currentState ?
$cfg['xSpaceAfter'] : '',
1139 'ySpaceBefore' => $currentState ?
$cfg['ySpaceBefore'] : '',
1140 'ySpaceAfter' => $currentState ?
$cfg['ySpaceAfter'] : '',
1144 // Initialize new settings:
1145 $currentState = $inRange;
1149 // Add char to bank:
1150 $bankAccum .= $utfChar;
1153 // Set result for FINAL part:
1154 if (strlen($bankAccum)) {
1155 $newResult[] = array(
1156 'str' => $bankAccum,
1157 'fontSize' => $currentState && $cfg['fontSize'] ?
$cfg['fontSize'] : $part['fontSize'],
1158 'fontFile' => $currentState && $cfg['fontFile'] ?
$cfg['fontFile'] : $part['fontFile'],
1159 'color' => $currentState ?
$cfg['color'] : '',
1160 'xSpaceBefore' => $currentState ?
$cfg['xSpaceBefore'] : '',
1161 'xSpaceAfter' => $currentState ?
$cfg['xSpaceAfter'] : '',
1162 'ySpaceBefore' => $currentState ?
$cfg['ySpaceBefore'] : '',
1163 'ySpaceAfter' => $currentState ?
$cfg['ySpaceAfter'] : '',
1168 // Set the new result as result array:
1169 if (count($newResult)) {
1170 $result = $newResult;
1182 * Calculates the spacing and wordSpacing values
1184 * @param array TypoScript array for the TEXT GIFBUILDER object
1185 * @param integer TypoScript value from eg $conf['niceText.']['scaleFactor']
1186 * @return array Array with two keys [0]/[1] being array($spacing,$wordSpacing)
1190 function calcWordSpacing($conf, $scaleFactor = 1) {
1192 $spacing = intval($conf['spacing']);
1193 $wordSpacing = intval($conf['wordSpacing']);
1194 $wordSpacing = $wordSpacing ?
$wordSpacing : $spacing * 2;
1196 $spacing *= $scaleFactor;
1197 $wordSpacing *= $scaleFactor;
1199 return array($spacing, $wordSpacing);
1203 * Calculates and returns the niceText.scaleFactor
1205 * @param array TypoScript array for the TEXT GIFBUILDER object
1206 * @return integer TypoScript value from eg $conf['niceText.']['scaleFactor']
1209 function getTextScalFactor($conf) {
1210 if (!$conf['niceText']) {
1212 } else { // NICETEXT::
1213 $sF = t3lib_div
::intInRange($conf['niceText.']['scaleFactor'], 2, 5);
1219 * Renders a regular text and takes care of a possible line break automatically.
1221 * @param pointer (See argument for PHP function imageTTFtext())
1222 * @param integer (See argument for PHP function imageTTFtext())
1223 * @param integer (See argument for PHP function imageTTFtext())
1224 * @param integer (See argument for PHP function imageTTFtext())
1225 * @param integer (See argument for PHP function imageTTFtext())
1226 * @param integer (See argument for PHP function imageTTFtext())
1227 * @param string (See argument for PHP function imageTTFtext())
1228 * @param string (See argument for PHP function imageTTFtext()). UTF-8 string, possibly with entities in.
1229 * @param array Split-rendering configuration
1230 * @param integer Scale factor
1231 * @param array $conf: The configuration
1234 protected function renderTTFText(&$im, $fontSize, $angle, $x, $y, $color, $fontFile, $string, $splitRendering, $conf, $sF = 1) {
1235 if (isset($conf['breakWidth']) && $conf['breakWidth'] && $this->getRenderedTextWidth($string, $conf) > $conf['breakWidth']) {
1239 $breakWidth = $conf['breakWidth'];
1240 $breakSpace = $this->getBreakSpace($conf);
1242 $wordPairs = $this->getWordPairsForLineBreak($string);
1243 // Iterate through all word pairs:
1244 foreach ($wordPairs as $index => $wordPair) {
1245 $wordWidth = $this->getRenderedTextWidth($wordPair, $conf);
1246 if ($index == 0 ||
$currentWidth +
$wordWidth <= $breakWidth) {
1247 $currentWidth +
= $wordWidth;
1248 $phrase .= $wordPair;
1250 // Render the current phrase that is below breakWidth:
1251 $this->ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $color, $fontFile, $phrase, $splitRendering, $sF);
1252 // Calculate the news height offset:
1254 // Restart the phrase:
1255 $currentWidth = $wordWidth;
1256 $phrase = $wordPair;
1259 // Render the remaining phrase:
1260 if ($currentWidth) {
1261 $this->ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $color, $fontFile, $phrase, $splitRendering, $sF);
1264 $this->ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $color, $fontFile, $string, $splitRendering, $sF);
1269 * Gets the word pairs used for automatic line breaks.
1271 * @param string $string
1274 protected function getWordPairsForLineBreak($string) {
1275 $wordPairs = array();
1277 $wordsArray = preg_split('#([- .,!:]+)#', $string, -1, PREG_SPLIT_DELIM_CAPTURE
);
1278 $wordsCount = count($wordsArray);
1279 for ($index = 0; $index < $wordsCount; $index +
= 2) {
1280 $wordPairs[] = $wordsArray[$index] . $wordsArray[$index +
1];
1287 * Gets the rendered text width.
1289 * @param string $text
1290 * @param array $conf
1293 protected function getRenderedTextWidth($text, $conf) {
1294 $bounds = $this->ImageTTFBBoxWrapper($conf['fontSize'], $conf['angle'], $conf['fontFile'], $this->recodeString($text), $conf['splitRendering.']);
1295 if ($conf['angle'] < 0) {
1296 $pixelWidth = abs($bounds[4] - $bounds[0]);
1297 } elseif ($conf['angle'] > 0) {
1298 $pixelWidth = abs($bounds[2] - $bounds[6]);
1300 $pixelWidth = abs($bounds[4] - $bounds[6]);
1306 * Gets the break space for each new line.
1308 * @param array $conf: TypoScript configuration for the currently rendered object
1309 * @param array $boundingBox: The bounding box the the currently rendered object
1310 * @return integer The break space
1312 protected function getBreakSpace($conf, array $boundingBox = NULL) {
1313 if (!isset($boundingBox)) {
1314 $boundingBox = $this->calcBBox($conf);
1315 $boundingBox = $boundingBox[2];
1318 if (isset($conf['breakSpace']) && $conf['breakSpace']) {
1319 $breakSpace = $boundingBox['lineHeight'] * $conf['breakSpace'];
1321 $breakSpace = $boundingBox['lineHeight'];
1328 /*********************************************
1330 * Other GIFBUILDER objects related to TEXT
1332 *********************************************/
1335 * Implements the "OUTLINE" GIFBUILDER object / property for the TEXT object
1337 * @param pointer GDlib image pointer
1338 * @param array TypoScript array with configuration for the GIFBUILDER object.
1339 * @param array The current working area coordinates.
1340 * @param array TypoScript array with configuration for the associated TEXT GIFBUILDER object.
1342 * @see tslib_gifBuilder::make(), makeText()
1344 function makeOutline(&$im, $conf, $workArea, $txtConf) {
1345 $thickness = intval($conf['thickness']);
1347 $txtConf['fontColor'] = $conf['color'];
1348 $outLineDist = t3lib_div
::intInRange($thickness, 1, 2);
1349 for ($b = 1; $b <= $outLineDist; $b++
) {
1355 $outL = $this->circleOffset($b, $it);
1356 for ($a = 0; $a < $it; $a++
) {
1357 $this->makeText($im, $txtConf, $this->applyOffset($workArea, $outL[$a]));
1364 * Creates some offset values in an array used to simulate a circularly applied outline around TEXT
1368 * @param integer Distance
1369 * @param integer Iterations.
1371 * @see makeOutline()
1373 function circleOffset($distance, $iterations) {
1375 if ($distance && $iterations) {
1376 for ($a = 0; $a < $iterations; $a++
) {
1377 $yOff = round(sin(2 * pi() / $iterations * ($a +
1)) * 100 * $distance);
1379 $yOff = intval(ceil(abs($yOff / 100)) * ($yOff / abs($yOff)));
1381 $xOff = round(cos(2 * pi() / $iterations * ($a +
1)) * 100 * $distance);
1383 $xOff = intval(ceil(abs($xOff / 100)) * ($xOff / abs($xOff)));
1385 $res[$a] = array($xOff, $yOff);
1392 * Implements the "EMBOSS" GIFBUILDER object / property for the TEXT object
1394 * @param pointer GDlib image pointer
1395 * @param array TypoScript array with configuration for the GIFBUILDER object.
1396 * @param array The current working area coordinates.
1397 * @param array TypoScript array with configuration for the associated TEXT GIFBUILDER object.
1399 * @see tslib_gifBuilder::make(), makeShadow()
1401 function makeEmboss(&$im, $conf, $workArea, $txtConf) {
1402 $conf['color'] = $conf['highColor'];
1403 $this->makeShadow($im, $conf, $workArea, $txtConf);
1404 $newOffset = t3lib_div
::intExplode(',', $conf['offset']);
1405 $newOffset[0] *= -1;
1406 $newOffset[1] *= -1;
1407 $conf['offset'] = implode(',', $newOffset);
1408 $conf['color'] = $conf['lowColor'];
1409 $this->makeShadow($im, $conf, $workArea, $txtConf);
1413 * Implements the "SHADOW" GIFBUILDER object / property for the TEXT object
1414 * The operation involves ImageMagick for combining.
1416 * @param pointer GDlib image pointer
1417 * @param array TypoScript array with configuration for the GIFBUILDER object.
1418 * @param array The current working area coordinates.
1419 * @param array TypoScript array with configuration for the associated TEXT GIFBUILDER object.
1421 * @see tslib_gifBuilder::make(), makeText(), makeEmboss()
1423 function makeShadow(&$im, $conf, $workArea, $txtConf) {
1424 $workArea = $this->applyOffset($workArea, t3lib_div
::intExplode(',', $conf['offset']));
1425 $blurRate = t3lib_div
::intInRange(intval($conf['blur']), 0, 99);
1427 if (!$blurRate ||
$this->NO_IM_EFFECTS
) { // No effects if ImageMagick ver. 5+
1428 $txtConf['fontColor'] = $conf['color'];
1429 $this->makeText($im, $txtConf, $workArea);
1433 $blurBorder = 3; // area around the blur used for cropping something
1434 $tmpStr = $this->randomName();
1435 $fileMenu = $tmpStr . '_menu.' . $this->gifExtension
;
1436 $fileColor = $tmpStr . '_color.' . $this->gifExtension
;
1437 $fileMask = $tmpStr . '_mask.' . $this->gifExtension
;
1439 // BlurColor Image laves
1440 $blurColImg = imagecreatetruecolor($w, $h);
1441 $bcols = $this->convertColor($conf['color']);
1442 $Bcolor = ImageColorAllocate($blurColImg, $bcols[0], $bcols[1], $bcols[2]);
1443 ImageFilledRectangle($blurColImg, 0, 0, $w, $h, $Bcolor);
1444 $this->ImageWrite($blurColImg, $fileColor);
1445 ImageDestroy($blurColImg);
1447 // The mask is made: BlurTextImage
1448 $blurTextImg = imagecreatetruecolor($w +
$blurBorder * 2, $h +
$blurBorder * 2);
1449 $Bcolor = ImageColorAllocate($blurTextImg, 0, 0, 0); // black background
1450 ImageFilledRectangle($blurTextImg, 0, 0, $w +
$blurBorder * 2, $h +
$blurBorder * 2, $Bcolor);
1451 $txtConf['fontColor'] = 'white';
1452 $blurBordArr = array($blurBorder, $blurBorder);
1453 $this->makeText($blurTextImg, $txtConf, $this->applyOffset($workArea, $blurBordArr));
1454 $this->ImageWrite($blurTextImg, $fileMask); // dump to temporary file
1455 ImageDestroy($blurTextImg); // destroy
1459 $command .= $this->maskNegate
;
1461 if ($this->V5_EFFECTS
) {
1462 $command .= $this->v5_blur($blurRate +
1);
1464 // Blurring of the mask
1465 $times = ceil($blurRate / 10); // How many blur-commands that is executed. Min = 1;
1466 $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.
1467 $newBlurRate = t3lib_div
::intInRange($newBlurRate, 1, 99);
1468 for ($a = 0; $a < $times; $a++
) { // Building blur-command
1469 $command .= ' -blur ' . $blurRate;
1473 $this->imageMagickExec($fileMask, $fileMask, $command . ' +matte');
1475 $blurTextImg_tmp = $this->imageCreateFromFile($fileMask); // the mask is loaded again
1476 if ($blurTextImg_tmp) { // if nothing went wrong we continue with the blurred mask
1478 // cropping the border from the mask
1479 $blurTextImg = imagecreatetruecolor($w, $h);
1480 $this->imagecopyresized($blurTextImg, $blurTextImg_tmp, 0, 0, $blurBorder, $blurBorder, $w, $h, $w, $h);
1481 ImageDestroy($blurTextImg_tmp); // Destroy the temporary mask
1485 if ($conf['intensity']) {
1486 $intensity = t3lib_div
::intInRange($conf['intensity'], 0, 100);
1488 $intensity = ceil(255 - ($intensity / 100 * 255));
1489 $this->inputLevels($blurTextImg, 0, $intensity, $this->maskNegate
);
1491 $opacity = t3lib_div
::intInRange(intval($conf['opacity']), 0, 100);
1492 if ($opacity && $opacity < 100) {
1493 $high = ceil(255 * $opacity / 100);
1494 $this->outputLevels($blurTextImg, 0, $high, $this->maskNegate
); // reducing levels as the opacity demands
1497 $this->ImageWrite($blurTextImg, $fileMask); // Dump the mask again
1498 ImageDestroy($blurTextImg); // Destroy the mask
1500 // The pictures are combined
1501 $this->ImageWrite($im, $fileMenu); // The main pictures is saved temporarily
1503 $this->combineExec($fileMenu, $fileColor, $fileMask, $fileMenu);
1505 $backIm = $this->imageCreateFromFile($fileMenu); // The main image is loaded again...
1506 if ($backIm) { // ... and if nothing went wrong we load it onto the old one.
1507 ImageColorTransparent($backIm, -1);
1511 // Deleting temporary files;
1512 if (!$this->dontUnlinkTempFiles
) {
1521 /****************************
1523 * Other GIFBUILDER objects
1525 ****************************/
1528 * Implements the "BOX" GIFBUILDER object
1530 * @param pointer GDlib image pointer
1531 * @param array TypoScript array with configuration for the GIFBUILDER object.
1532 * @param array The current working area coordinates.
1534 * @see tslib_gifBuilder::make()
1536 function makeBox(&$im, $conf, $workArea) {
1537 $cords = t3lib_div
::intExplode(',', $conf['dimensions'] . ',,,');
1538 $conf['offset'] = $cords[0] . ',' . $cords[1];
1539 $cords = $this->objPosition($conf, $workArea, array($cords[2], $cords[3]));
1540 $cols = $this->convertColor($conf['color']);
1541 if (!$this->truecolor
) {
1542 $reduce = t3lib_div
::intInRange($this->setup
['reduceColors'], 256, $this->truecolorColors
, 256);
1543 $this->reduceColors($im, $reduce - 1, $reduce - 2); // If "reduce-1" colors (or more) are used reduce them to "reduce-2"
1547 if (isset($conf['opacity'])) {
1549 // PHP 0 = opaque, 127 = transparent
1550 // TYPO3 100 = opaque, 0 = transparent
1551 $opacity = t3lib_div
::intInRange(intval($conf['opacity']), 1, 100, 1);
1552 $opacity = abs($opacity - 100);
1553 $opacity = round((127 * $opacity) / 100);
1556 $tmpColor = ImageColorAllocateAlpha($im, $cols[0], $cols[1], $cols[2], $opacity);
1557 imagefilledrectangle($im, $cords[0], $cords[1], $cords[0] +
$cords[2] - 1, $cords[1] +
$cords[3] - 1, $tmpColor);
1561 * Implements the "Ellipse" GIFBUILDER object
1562 * Example Typoscript:
1569 * 10.dimensions = 100,100,50,50
1573 * $conf['dimensions'] = offset x, offset y, width of ellipse, height of ellipse
1575 * @param pointer GDlib image pointer
1576 * @param array $conf TypoScript array with configuration for the GIFBUILDER object.
1577 * @param array $workArea The current working area coordinates.
1579 * @see tslib_gifBuilder::make()
1581 public function makeEllipse(&$im, array $conf, array $workArea) {
1582 $ellipseConfiguration = t3lib_div
::intExplode(',', $conf['dimensions'] . ',,,');
1583 $conf['offset'] = $ellipseConfiguration[0] . ',' . $ellipseConfiguration[1]; // ellipse offset inside workArea (x/y)
1586 $imageCoordinates = $this->objPosition($conf, $workArea, array($ellipseConfiguration[2], $ellipseConfiguration[3]));
1588 $color = $this->convertColor($conf['color']);
1589 $fillingColor = imagecolorallocate($im, $color[0], $color[1], $color[2]);
1590 imagefilledellipse($im, $imageCoordinates[0], $imageCoordinates[1], $imageCoordinates[2], $imageCoordinates[3], $fillingColor);
1594 * Implements the "EFFECT" GIFBUILDER object
1595 * The operation involves ImageMagick for applying effects
1597 * @param pointer GDlib image pointer
1598 * @param array TypoScript array with configuration for the GIFBUILDER object.
1600 * @see tslib_gifBuilder::make(), applyImageMagickToPHPGif()
1602 function makeEffect(&$im, $conf) {
1603 $commands = $this->IMparams($conf['value']);
1605 $this->applyImageMagickToPHPGif($im, $commands);
1610 * Creating ImageMagick paramters from TypoScript property
1612 * @param string A string with effect keywords=value pairs separated by "|"
1613 * @return string ImageMagick prepared parameters.
1617 function IMparams($setup) {
1618 if (!trim($setup)) {
1621 $effects = explode('|', $setup);
1623 foreach ($effects as $val) {
1624 $pairs = explode('=', $val, 2);
1625 $value = trim($pairs[1]);
1626 $effect = strtolower(trim($pairs[0]));
1629 $commands .= ' -gamma ' . doubleval($value);
1632 if (!$this->NO_IM_EFFECTS
) {
1633 if ($this->V5_EFFECTS
) {
1634 $commands .= $this->v5_blur($value);
1636 $commands .= ' -blur ' . t3lib_div
::intInRange($value, 1, 99);
1641 if (!$this->NO_IM_EFFECTS
) {
1642 if ($this->V5_EFFECTS
) {
1643 $commands .= $this->v5_sharpen($value);
1645 $commands .= ' -sharpen ' . t3lib_div
::intInRange($value, 1, 99);
1650 $commands .= ' -rotate ' . t3lib_div
::intInRange($value, 0, 360);
1653 $commands .= ' -solarize ' . t3lib_div
::intInRange($value, 0, 99);
1656 $commands .= ' -swirl ' . t3lib_div
::intInRange($value, 0, 1000);
1659 $params = t3lib_div
::intExplode(',', $value);
1660 $commands .= ' -wave ' . t3lib_div
::intInRange($params[0], 0, 99) . 'x' . t3lib_div
::intInRange($params[1], 0, 99);
1663 $commands .= ' -charcoal ' . t3lib_div
::intInRange($value, 0, 100);
1666 $commands .= ' -colorspace GRAY';
1669 $commands .= ' -edge ' . t3lib_div
::intInRange($value, 0, 99);
1672 $commands .= ' -emboss';
1675 $commands .= ' -flip';
1678 $commands .= ' -flop';
1681 $commands .= ' -colors ' . t3lib_div
::intInRange($value, 2, 255);
1684 $commands .= ' -shear ' . t3lib_div
::intInRange($value, -90, 90);
1687 $commands .= ' -negate';
1695 * Implements the "ADJUST" GIFBUILDER object
1697 * @param pointer GDlib image pointer
1698 * @param array TypoScript array with configuration for the GIFBUILDER object.
1700 * @see tslib_gifBuilder::make(), autoLevels(), outputLevels(), inputLevels()
1702 function adjust(&$im, $conf) {
1703 $setup = $conf['value'];
1704 if (!trim($setup)) {
1707 $effects = explode('|', $setup);
1708 foreach ($effects as $val) {
1709 $pairs = explode('=', $val, 2);
1710 $value = trim($pairs[1]);
1711 $effect = strtolower(trim($pairs[0]));
1713 case 'inputlevels': // low,high
1714 $params = t3lib_div
::intExplode(',', $value);
1715 $this->inputLevels($im, $params[0], $params[1]);
1717 case 'outputlevels':
1718 $params = t3lib_div
::intExplode(',', $value);
1719 $this->outputLevels($im, $params[0], $params[1]);
1722 $this->autoLevels($im);
1729 * Implements the "CROP" GIFBUILDER object
1731 * @param pointer GDlib image pointer
1732 * @param array TypoScript array with configuration for the GIFBUILDER object.
1734 * @see tslib_gifBuilder::make()
1736 function crop(&$im, $conf) {
1737 $this->setWorkArea(''); // clears workArea to total image
1738 $cords = t3lib_div
::intExplode(',', $conf['crop'] . ',,,');
1739 $conf['offset'] = $cords[0] . ',' . $cords[1];
1740 $cords = $this->objPosition($conf, $this->workArea
, array($cords[2], $cords[3]));
1742 $newIm = imagecreatetruecolor($cords[2], $cords[3]);
1743 $cols = $this->convertColor($conf['backColor'] ?
$conf['backColor'] : $this->setup
['backColor']);
1744 $Bcolor = ImageColorAllocate($newIm, $cols[0], $cols[1], $cols[2]);
1745 ImageFilledRectangle($newIm, 0, 0, $cords[2], $cords[3], $Bcolor);
1748 $workArea = array(0, 0, $cords[2], $cords[3]);
1749 if ($cords[0] < 0) {
1750 $workArea[0] = abs($cords[0]);
1752 $newConf['offset'] = -$cords[0];
1754 if ($cords[1] < 0) {
1755 $workArea[1] = abs($cords[1]);
1757 $newConf['offset'] .= ',' . -$cords[1];
1760 $this->copyGifOntoGif($newIm, $im, $newConf, $workArea);
1762 $this->w
= imagesx($im);
1763 $this->h
= imagesy($im);
1764 $this->setWorkArea(''); // clears workArea to total image
1768 * Implements the "SCALE" GIFBUILDER object
1770 * @param pointer GDlib image pointer
1771 * @param array TypoScript array with configuration for the GIFBUILDER object.
1773 * @see tslib_gifBuilder::make()
1775 function scale(&$im, $conf) {
1776 if ($conf['width'] ||
$conf['height'] ||
$conf['params']) {
1777 $tmpStr = $this->randomName();
1778 $theFile = $tmpStr . '.' . $this->gifExtension
;
1779 $this->ImageWrite($im, $theFile);
1780 $theNewFile = $this->imageMagickConvert($theFile, $this->gifExtension
, $conf['width'], $conf['height'], $conf['params'], '', '');
1781 $tmpImg = $this->imageCreateFromFile($theNewFile[3]);
1785 $this->w
= imagesx($im);
1786 $this->h
= imagesy($im);
1787 $this->setWorkArea(''); // clears workArea to total image
1789 if (!$this->dontUnlinkTempFiles
) {
1791 if ($theNewFile[3] && $theNewFile[3] != $theFile) {
1792 unlink($theNewFile[3]);
1799 * Implements the "WORKAREA" GIFBUILDER object when setting it
1800 * Setting internal working area boundaries (->workArea)
1802 * @param string Working area dimensions, comma separated
1805 * @see tslib_gifBuilder::make()
1807 function setWorkArea($workArea) {
1808 $this->workArea
= t3lib_div
::intExplode(',', $workArea);
1809 $this->workArea
= $this->applyOffset($this->workArea
, $this->OFFSET
);
1810 if (!$this->workArea
[2]) {
1811 $this->workArea
[2] = $this->w
;
1813 if (!$this->workArea
[3]) {
1814 $this->workArea
[3] = $this->h
;
1819 /*************************
1821 * Adjustment functions
1823 ************************/
1826 * Apply auto-levels to input image pointer
1828 * @param integer GDlib Image Pointer
1831 function autolevels(&$im) {
1832 $totalCols = ImageColorsTotal($im);
1835 for ($c = 0; $c < $totalCols; $c++
) {
1836 $cols = ImageColorsForIndex($im, $c);
1837 $grayArr[] = round(($cols['red'] +
$cols['green'] +
$cols['blue']) / 3);
1839 $min = min($grayArr);
1840 $max = max($grayArr);
1841 $delta = $max - $min;
1843 for ($c = 0; $c < $totalCols; $c++
) {
1844 $cols = ImageColorsForIndex($im, $c);
1845 $cols['red'] = floor(($cols['red'] - $min) / $delta * 255);
1846 $cols['green'] = floor(($cols['green'] - $min) / $delta * 255);
1847 $cols['blue'] = floor(($cols['blue'] - $min) / $delta * 255);
1848 ImageColorSet($im, $c, $cols['red'], $cols['green'], $cols['blue']);
1854 * Apply output levels to input image pointer (decreasing contrast)
1856 * @param integer GDlib Image Pointer
1857 * @param integer The "low" value (close to 0)
1858 * @param integer The "high" value (close to 255)
1859 * @param boolean If swap, then low and high are swapped. (Useful for negated masks...)
1862 function outputLevels(&$im, $low, $high, $swap = '') {
1864 $low = t3lib_div
::intInRange($low, 0, 255);
1865 $high = t3lib_div
::intInRange($high, 0, 255);
1870 $high = 255 - $temp;
1873 $delta = $high - $low;
1874 $totalCols = ImageColorsTotal($im);
1875 for ($c = 0; $c < $totalCols; $c++
) {
1876 $cols = ImageColorsForIndex($im, $c);
1877 $cols['red'] = $low +
floor($cols['red'] / 255 * $delta);
1878 $cols['green'] = $low +
floor($cols['green'] / 255 * $delta);
1879 $cols['blue'] = $low +
floor($cols['blue'] / 255 * $delta);
1880 ImageColorSet($im, $c, $cols['red'], $cols['green'], $cols['blue']);
1886 * Apply input levels to input image pointer (increasing contrast)
1888 * @param integer GDlib Image Pointer
1889 * @param integer The "low" value (close to 0)
1890 * @param integer The "high" value (close to 255)
1891 * @param boolean If swap, then low and high are swapped. (Useful for negated masks...)
1894 function inputLevels(&$im, $low, $high, $swap = '') {
1896 $low = t3lib_div
::intInRange($low, 0, 255);
1897 $high = t3lib_div
::intInRange($high, 0, 255);
1902 $high = 255 - $temp;
1905 $delta = $high - $low;
1906 $totalCols = ImageColorsTotal($im);
1907 for ($c = 0; $c < $totalCols; $c++
) {
1908 $cols = ImageColorsForIndex($im, $c);
1909 $cols['red'] = t3lib_div
::intInRange(($cols['red'] - $low) / $delta * 255, 0, 255);
1910 $cols['green'] = t3lib_div
::intInRange(($cols['green'] - $low) / $delta * 255, 0, 255);
1911 $cols['blue'] = t3lib_div
::intInRange(($cols['blue'] - $low) / $delta * 255, 0, 255);
1912 ImageColorSet($im, $c, $cols['red'], $cols['green'], $cols['blue']);
1918 * Reduce colors in image dependend on the actual amount of colors (Only works if we are not in truecolor mode)
1919 * This function is not needed anymore, as truecolor is now always on.
1921 * @param integer GDlib Image Pointer
1922 * @param integer The max number of colors in the image before a reduction will happen; basically this means that IF the GD image current has the same amount or more colors than $limit define, THEN a reduction is performed.
1923 * @param integer Number of colors to reduce the image to.
1925 * @deprecated since TYPO3 4.4, this function will be removed in TYPO3 4.6.
1927 function reduceColors(&$im, $limit, $cols) {
1928 t3lib_div
::logDeprecatedFunction();
1930 if (!$this->truecolor
&& ImageColorsTotal($im) >= $limit) {
1931 $this->makeEffect($im, array('value' => 'colors=' . $cols));
1936 * Reduce colors in image using IM and create a palette based image if possible (<=256 colors)
1938 * @param string Image file to reduce
1939 * @param integer Number of colors to reduce the image to.
1940 * @return string Reduced file
1942 function IMreduceColors($file, $cols) {
1943 $fI = t3lib_div
::split_fileref($file);
1944 $ext = strtolower($fI['fileext']);
1945 $result = $this->randomName() . '.' . $ext;
1946 if (($reduce = t3lib_div
::intInRange($cols, 0, ($ext == 'gif' ?
256 : $this->truecolorColors
), 0)) > 0) {
1947 $params = ' -colors ' . $reduce;
1948 if (!$this->im_version_4
) {
1949 // IM4 doesn't have this options but forces them automatically if applicaple (<256 colors in image)
1950 if ($reduce <= 256) {
1951 $params .= ' -type Palette';
1953 if ($ext == 'png' && $reduce <= 256) {
1957 $this->imageMagickExec($file, $prefix . $result, $params);
1966 /*********************************
1968 * GIFBUILDER Helper functions
1970 *********************************/
1973 * Checks if the $fontFile is already at an absolute path and if not, prepends the correct path.
1974 * Use PATH_site unless we are in the backend.
1975 * Call it by t3lib_stdGraphic::prependAbsolutePath()
1977 * @param string The font file
1978 * @return string The font file with absolute path.
1980 function prependAbsolutePath($fontFile) {
1981 $absPath = defined('PATH_typo3') ?
dirname(PATH_thisScript
) . '/' : PATH_site
;
1982 $fontFile = t3lib_div
::isAbsPath($fontFile) ?
$fontFile : t3lib_div
::resolveBackPath($absPath . $fontFile);
1987 * Returns the IM command for sharpening with ImageMagick 5 (when $this->V5_EFFECTS is set).
1988 * Uses $this->im5fx_sharpenSteps for translation of the factor to an actual command.
1990 * @param integer The sharpening factor, 0-100 (effectively in 10 steps)
1991 * @return string The sharpening command, eg. " -sharpen 3x4"
1992 * @see makeText(), IMparams(), v5_blur()
1994 function v5_sharpen($factor) {
1995 $factor = t3lib_div
::intInRange(ceil($factor / 10), 0, 10);
1997 $sharpenArr = explode(',', ',' . $this->im5fx_sharpenSteps
);
1998 $sharpenF = trim($sharpenArr[$factor]);
2000 $cmd = ' -sharpen ' . $sharpenF;
2006 * Returns the IM command for blurring with ImageMagick 5 (when $this->V5_EFFECTS is set).
2007 * Uses $this->im5fx_blurSteps for translation of the factor to an actual command.
2009 * @param integer The blurring factor, 0-100 (effectively in 10 steps)
2010 * @return string The blurring command, eg. " -blur 3x4"
2011 * @see makeText(), IMparams(), v5_sharpen()
2013 function v5_blur($factor) {
2014 $factor = t3lib_div
::intInRange(ceil($factor / 10), 0, 10);
2016 $blurArr = explode(',', ',' . $this->im5fx_blurSteps
);
2017 $blurF = trim($blurArr[$factor]);
2019 $cmd = ' -blur ' . $blurF;
2025 * Returns a random filename prefixed with "temp_" and then 32 char md5 hash (without extension) from $this->tempPath.
2026 * 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.
2030 function randomName() {
2031 $this->createTempSubDir('temp/');
2032 return $this->tempPath
. 'temp/' . md5(uniqid(''));
2036 * Applies offset value to coordinated in $cords.
2037 * Basically the value of key 0/1 of $OFFSET is added to keys 0/1 of $cords
2039 * @param array Integer coordinates in key 0/1
2040 * @param array Offset values in key 0/1
2041 * @return array Modified $cords array
2043 function applyOffset($cords, $OFFSET) {
2044 $cords[0] = intval($cords[0]) +
intval($OFFSET[0]);
2045 $cords[1] = intval($cords[1]) +
intval($OFFSET[1]);
2050 * Converts a "HTML-color" TypoScript datatype to RGB-values.
2053 * @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
2054 * @return array RGB values in key 0/1/2 of the array
2056 function convertColor($string) {
2058 $cParts = explode(':', $string, 2);
2060 // Finding the RGB definitions of the color:
2061 $string = $cParts[0];
2062 if (strstr($string, '#')) {
2063 $string = preg_replace('/[^A-Fa-f0-9]*/', '', $string);
2064 $col[] = HexDec(substr($string, 0, 2));
2065 $col[] = HexDec(substr($string, 2, 2));
2066 $col[] = HexDec(substr($string, 4, 2));
2067 } elseif (strstr($string, ',')) {
2068 $string = preg_replace('/[^,0-9]*/', '', $string);
2069 $strArr = explode(',', $string);
2070 $col[] = intval($strArr[0]);
2071 $col[] = intval($strArr[1]);
2072 $col[] = intval($strArr[2]);
2074 $string = strtolower(trim($string));
2075 if ($this->colMap
[$string]) {
2076 $col = $this->colMap
[$string];
2078 $col = array(0, 0, 0);
2081 // ... and possibly recalculating the value
2082 if (trim($cParts[1])) {
2083 $cParts[1] = trim($cParts[1]);
2084 if (substr($cParts[1], 0, 1) == '*') {
2085 $val = doubleval(substr($cParts[1], 1));
2086 $col[0] = t3lib_div
::intInRange($col[0] * $val, 0, 255);
2087 $col[1] = t3lib_div
::intInRange($col[1] * $val, 0, 255);
2088 $col[2] = t3lib_div
::intInRange($col[2] * $val, 0, 255);
2090 $val = intval($cParts[1]);
2091 $col[0] = t3lib_div
::intInRange($col[0] +
$val, 0, 255);
2092 $col[1] = t3lib_div
::intInRange($col[1] +
$val, 0, 255);
2093 $col[2] = t3lib_div
::intInRange($col[2] +
$val, 0, 255);
2101 * Used with text strings for fonts when languages has other character sets.
2103 * @param string The text to recode
2104 * @return string The recoded string. Should be UTF-8 output. MAY contain entities (eg. { or &#quot; which should render as real chars).
2106 function recodeString($string) {
2107 // Recode string to UTF-8 from $this->nativeCharset:
2108 if ($this->nativeCharset
&& $this->nativeCharset
!= 'utf-8') {
2109 $string = $this->csConvObj
->utf8_encode($string, $this->nativeCharset
); // Convert to UTF-8
2112 // Recode string accoding to TTFLocaleConv. Deprecated.
2113 if ($this->TTFLocaleConv
) {
2114 t3lib_div
::deprecationLog('The option $TYPO3_CONF_VARS[\'GFX\'][\'TTFLocaleConv\'] is in use, but deprecated since TYPO3 3.6, will be removed in TYPO3 4.6. Make sure to unset this variable in your typo3conf/localconf.php and use a different way to encode your string.');
2116 list($from, $to) = t3lib_div
::trimExplode('..', $this->TTFLocaleConv
, TRUE);
2117 $string = $this->csConvObj
->conv($string, $from, $to);
2124 * Split a string into an array of individual characters
2125 * 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.
2127 * @param string The text string to split
2128 * @param boolean Return Unicode numbers instead of chars.
2129 * @return array Numerical array with a char as each value.
2131 function singleChars($theText, $returnUnicodeNumber = FALSE) {
2132 if ($this->nativeCharset
) {
2133 return $this->csConvObj
->utf8_to_numberarray($theText, 1, $returnUnicodeNumber ?
0 : 1); // Get an array of separated UTF-8 chars
2136 $c = strlen($theText);
2137 for ($a = 0; $a < $c; $a++
) {
2138 $output[] = substr($theText, $a, 1);
2145 * 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
2147 * @param array TypoScript configuration for a GIFBUILDER object
2148 * @param array Workarea definition
2149 * @param array BB (Bounding box) array. Not just used for TEXT objects but also for others
2150 * @return array [0]=x, [1]=y, [2]=w, [3]=h
2152 * @see copyGifOntoGif(), makeBox(), crop()
2154 function objPosition($conf, $workArea, $BB) {
2155 // offset, align, valign, workarea
2157 $result[2] = $BB[0];
2158 $result[3] = $BB[1];
2162 $align = explode(',', $conf['align']);
2163 $align[0] = strtolower(substr(trim($align[0]), 0, 1));
2164 $align[1] = strtolower(substr(trim($align[1]), 0, 1));
2166 switch ($align[0]) {
2168 $result[0] = $w - $result[2];
2171 $result[0] = round(($w - $result[2]) / 2);
2177 switch ($align[1]) {
2179 $result[1] = $h - $result[3]; // y pos
2182 $result[1] = round(($h - $result[3]) / 2);
2188 $result = $this->applyOffset($result, t3lib_div
::intExplode(',', $conf['offset']));
2189 $result = $this->applyOffset($result, $workArea);
2194 /***********************************
2196 * Scaling, Dimensions of images
2198 ***********************************/
2201 * Converts $imagefile to another file in temp-dir of type $newExt (extension).
2203 * @param string The image filepath
2204 * @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.
2205 * @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
2206 * @param string Height. See $w
2207 * @param string Additional ImageMagick parameters.
2208 * @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...
2209 * @param array An array with options passed to getImageScale (see this function).
2210 * @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.
2211 * @return array [0]/[1] is w/h, [2] is file extension and [3] is the filename.
2212 * @see getImageScale(), typo3/show_item.php, fileList_ext::renderImage(), tslib_cObj::getImgResource(), SC_tslib_showpic::show(), maskImageOntoImage(), copyImageOntoImage(), scale()
2214 function imageMagickConvert($imagefile, $newExt = '', $w = '', $h = '', $params = '', $frame = '', $options = '', $mustCreate = 0) {
2215 if ($this->NO_IMAGE_MAGICK
) {
2216 // Returning file info right away
2217 return $this->getImageDimensions($imagefile);
2220 if ($info = $this->getImageDimensions($imagefile)) {
2221 $newExt = strtolower(trim($newExt));
2222 if (!$newExt) { // If no extension is given the original extension is used
2225 if ($newExt == 'web') {
2226 if (t3lib_div
::inList($this->webImageExt
, $info[2])) {
2229 $newExt = $this->gif_or_jpg($info[2], $info[0], $info[1]);
2231 $params = $this->cmds
[$newExt];
2235 if (t3lib_div
::inList($this->imageFileExt
, $newExt)) {
2236 if (strstr($w . $h, 'm')) {
2242 $data = $this->getImageScale($info, $w, $h, $options);
2243 $w = $data['origW'];
2244 $h = $data['origH'];
2246 // if no conversion should be performed
2247 // this flag is true if the width / height does NOT dictate
2248 // the image to be scaled!! (that is if no width / height is
2249 // given or if the destination w/h matches the original image
2250 // dimensions or if the option to not scale the image is set)
2251 $noScale = (!$w && !$h) ||
($data[0] == $info[0] && $data[1] == $info[1]) ||
$options['noScale'];
2253 if ($noScale && !$data['crs'] && !$params && !$frame && $newExt == $info[2] && !$mustCreate) {
2254 // set the new width and height before returning,
2255 // if the noScale option is set
2256 if ($options['noScale']) {
2257 $info[0] = $data[0];
2258 $info[1] = $data[1];
2260 $info[3] = $imagefile;
2263 $info[0] = $data[0];
2264 $info[1] = $data[1];
2266 $frame = $this->noFramePrepended ?
'' : intval($frame);
2269 $params = $this->cmds
[$newExt];
2274 if (!$data['origW']) {
2275 $data['origW'] = $data[0];
2277 if (!$data['origH']) {
2278 $data['origH'] = $data[1];
2280 $offsetX = intval(($data[0] - $data['origW']) * ($data['cropH'] +
100) / 200);
2281 $offsetY = intval(($data[1] - $data['origH']) * ($data['cropV'] +
100) / 200);
2282 $params .= ' -crop ' . $data['origW'] . 'x' . $data['origH'] . '+' . $offsetX . '+' . $offsetY . ' ';
2285 $command = $this->scalecmd
. ' ' . $info[0] . 'x' . $info[1] . '! ' . $params . ' ';
2286 $cropscale = ($data['crs'] ?
'crs-V' . $data['cropV'] . 'H' . $data['cropH'] : '');
2288 if ($this->alternativeOutputKey
) {
2289 $theOutputName = t3lib_div
::shortMD5($command . $cropscale . basename($imagefile) . $this->alternativeOutputKey
. '[' . $frame . ']');
2291 $theOutputName = t3lib_div
::shortMD5($command . $cropscale . $imagefile . filemtime($imagefile) . '[' . $frame . ']');
2293 if ($this->imageMagickConvert_forceFileNameBody
) {
2294 $theOutputName = $this->imageMagickConvert_forceFileNameBody
;
2295 $this->imageMagickConvert_forceFileNameBody
= '';
2298 // Making the temporary filename:
2299 $this->createTempSubDir('pics/');
2300 $output = $this->absPrefix
. $this->tempPath
. 'pics/' . $this->filenamePrefix
. $theOutputName . '.' . $newExt;
2302 // Register temporary filename:
2303 $GLOBALS['TEMP_IMAGES_ON_PAGE'][] = $output;
2305 if ($this->dontCheckForExistingTempFile ||
!$this->file_exists_typo3temp_file($output, $imagefile)) {
2306 $this->imageMagickExec($imagefile, $output, $command, $frame);
2308 if (file_exists($output)) {
2311 if ($params) { // params could realisticly change some imagedata!
2312 $info = $this->getImageDimensions($info[3]);
2314 if ($info[2] == $this->gifExtension
&& !$this->dontCompress
) {
2315 t3lib_div
::gif_compress($info[3], ''); // Compress with IM (lzw) or GD (rle) (Workaround for the absence of lzw-compression in GD)
2324 * Gets the input image dimensions.
2326 * @param string The image filepath
2327 * @return array Returns an array where [0]/[1] is w/h, [2] is extension and [3] is the filename.
2328 * @see imageMagickConvert(), tslib_cObj::getImgResource()
2330 function getImageDimensions($imageFile) {
2331 preg_match('/([^\.]*)$/', $imageFile, $reg);
2332 if (file_exists($imageFile) && t3lib_div
::inList($this->imageFileExt
, strtolower($reg[0]))) {
2333 if ($returnArr = $this->getCachedImageDimensions($imageFile)) {
2336 if ($temp = @getImageSize
($imageFile)) {
2337 $returnArr = array($temp[0], $temp[1], strtolower($reg[0]), $imageFile);
2339 $returnArr = $this->imageMagickIdentify($imageFile);
2342 $this->cacheImageDimensions($returnArr);
2351 * Cache the result of the getImageDimensions function into the database. Does not check if the
2354 * @param array $identifyResult: Result of the getImageDimensions function
2355 * @return boolean True if operation was successful
2356 * @author Michael Stucki <michael@typo3.org> / Robert Lemke <rl@robertlemke.de>
2358 function cacheImageDimensions($identifyResult) {
2360 // Create a md5 hash of the filename
2361 $md5Hash = md5_file($identifyResult[3]);
2364 'md5hash' => $md5Hash,
2365 'md5filename' => md5($identifyResult[3]),
2366 'tstamp' => $GLOBALS['EXEC_TIME'],
2367 'filename' => $identifyResult[3],
2368 'imagewidth' => $identifyResult[0],
2369 'imageheight' => $identifyResult[1],
2371 $TYPO3_DB->exec_INSERTquery('cache_imagesizes', $fieldArr);
2372 if (!$err = $TYPO3_DB->sql_error()) {
2380 * Fetch the cached imageDimensions from the MySQL database. Does not check if the image file exists!
2382 * @param string The image filepath
2383 * @return array Returns an array where [0]/[1] is w/h, [2] is extension and [3] is the filename.
2384 * @author Michael Stucki <michael@typo3.org> / Robert Lemke <rl@robertlemke.de>
2386 function getCachedImageDimensions($imageFile) {
2388 // Create a md5 hash of the filename
2389 $md5Hash = md5_file($imageFile);
2390 preg_match('/([^\.]*)$/', $imageFile, $reg);
2391 $res = $TYPO3_DB->exec_SELECTquery('md5hash, imagewidth, imageheight', 'cache_imagesizes', 'md5filename=' . $TYPO3_DB->fullQuoteStr(md5($imageFile), 'cache_imagesizes'));
2393 if ($row = $TYPO3_DB->sql_fetch_assoc($res)) {
2394 if ($row['md5hash'] != $md5Hash) {
2395 // file has changed, delete the row
2396 $TYPO3_DB->exec_DELETEquery('cache_imagesizes', 'md5hash=' . $TYPO3_DB->fullQuoteStr($row['md5hash'], 'cache_imagesizes'));
2398 return (array((int) $row['imagewidth'], (int) $row['imageheight'], strtolower($reg[0]), $imageFile));
2406 * Get numbers for scaling the image based on input
2408 * @param array Current image information: Width, Height etc.
2409 * @param integer "required" width
2410 * @param integer "required" height
2411 * @param array Options: Keys are like "maxW", "maxH", "minW", "minH"
2414 * @see imageMagickConvert()
2416 function getImageScale($info, $w, $h, $options) {
2417 if (strstr($w . $h, 'm')) {
2423 if (strstr($w . $h, 'c')) {
2424 $out['cropH'] = intval(substr(strstr($w, 'c'), 1));
2425 $out['cropV'] = intval(substr(strstr($h, 'c'), 1));
2434 // if there are max-values...
2435 if ($options['maxW']) {
2436 if ($w) { // if width is given...
2437 if ($w > $options['maxW']) {
2438 $w = $options['maxW'];
2439 $max = 1; // height should follow
2442 if ($info[0] > $options['maxW']) {
2443 $w = $options['maxW'];
2444 $max = 1; // height should follow
2448 if ($options['maxH']) {
2449 if ($h) { // if height is given...
2450 if ($h > $options['maxH']) {
2451 $h = $options['maxH'];
2452 $max = 1; // height should follow
2455 if ($info[1] > $options['maxH']) { // Changed [0] to [1] 290801
2456 $h = $options['maxH'];
2457 $max = 1; // height should follow
2465 if (!$this->mayScaleUp
) {
2466 if ($w > $info[0]) {
2469 if ($h > $info[1]) {
2473 if ($w ||
$h) { // if scaling should be performed
2475 $info[1] = ceil($info[1] * ($w / $info[0]));
2479 $info[0] = ceil($info[0] * ($h / $info[1]));
2484 $ratio = $info[0] / $info[1];
2485 if ($h * $ratio > $w) {
2486 $h = round($w / $ratio);
2488 $w = round($h * $ratio);
2492 $ratio = $info[0] / $info[1];
2493 if ($h * $ratio < $w) {
2494 $h = round($w / $ratio);
2496 $w = round($h * $ratio);
2505 // Set minimum-measures!
2506 if ($options['minW'] && $out[0] < $options['minW']) {
2507 if (($max ||
$crs) && $out[0]) {
2508 $out[1] = round($out[1] * $options['minW'] / $out[0]);
2510 $out[0] = $options['minW'];
2512 if ($options['minH'] && $out[1] < $options['minH']) {
2513 if (($max ||
$crs) && $out[1]) {
2514 $out[0] = round($out[0] * $options['minH'] / $out[1]);
2516 $out[1] = $options['minH'];
2523 * Used to check if a certain process of scaling an image is already being carried out (can be logged in the SQL database)
2525 * @param string Output imagefile
2526 * @param string Original basis file
2527 * @return boolean Returns true if the file is already being made; thus "true" means "Don't render the image again"
2530 function file_exists_typo3temp_file($output, $orig = '') {
2531 if ($this->enable_typo3temp_db_tracking
) {
2532 if (file_exists($output)) { // If file exists, then we return immediately
2534 } else { // If not, we look up in the cache_typo3temp_log table to see if there is a image being rendered right now.
2535 $md5Hash = md5($output);
2536 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
2538 'cache_typo3temp_log',
2539 'md5hash=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($md5Hash, 'cache_typo3temp_log') . ' AND tstamp>' . ($GLOBALS['EXEC_TIME'] - 30)
2541 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) { // If there was a record, the image is being generated by another proces (we assume)
2542 if (is_object($GLOBALS['TSFE'])) {
2543 $GLOBALS['TSFE']->set_no_cache();
2544 } // ...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...)
2545 if (is_object($GLOBALS['TT'])) {
2546 $GLOBALS['TT']->setTSlogMessage('typo3temp_log: Assume this file is being rendered now: ' . $output);
2548 return 2; // Return 'success - 2'
2549 } 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.
2551 $insertFields = array(
2552 'md5hash' => $md5Hash,
2553 'tstamp' => $GLOBALS['EXEC_TIME'],
2554 'filename' => $output,
2555 'orig_filename' => $orig
2557 $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_typo3temp_log', 'md5hash=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($md5Hash, 'cache_typo3temp_log'));
2558 $GLOBALS['TYPO3_DB']->exec_INSERTquery('cache_typo3temp_log', $insertFields);
2560 if (is_object($GLOBALS['TT'])) {
2561 $GLOBALS['TT']->setTSlogMessage('typo3temp_log: The row did not exist, so a new is written and file is being processed: ' . $output);
2567 return file_exists($output);
2572 /***********************************
2574 * ImageMagick API functions
2576 ***********************************/
2579 * Returns an array where [0]/[1] is w/h, [2] is extension and [3] is the filename.
2582 * @param string The relative (to PATH_site) image filepath
2585 function imageMagickIdentify($imagefile) {
2586 if (!$this->NO_IMAGE_MAGICK
) {
2587 $frame = $this->noFramePrepended ?
'' : '[0]';
2588 $cmd = t3lib_div
::imageMagickCommand('identify', $this->wrapFileName($imagefile) . $frame);
2589 $returnVal = array();
2590 exec($cmd, $returnVal);
2591 $splitstring = $returnVal[0];
2592 $this->IM_commands
[] = array('identify', $cmd, $returnVal[0]);
2594 preg_match('/([^\.]*)$/', $imagefile, $reg);
2595 $splitinfo = explode(' ', $splitstring);
2596 foreach ($splitinfo as $key => $val) {
2599 $temp = explode('x', $val);
2601 if (intval($temp[0]) && intval($temp[1])) {
2606 if ($dim[0] && $dim[1]) {
2607 return array($dim[0], $dim[1], strtolower($reg[0]), $imagefile);
2614 * Executes a ImageMagick "convert" on two filenames, $input and $output using $params before them.
2615 * Can be used for many things, mostly scaling and effects.
2617 * @param string The relative (to PATH_site) image filepath, input file (read from)
2618 * @param string The relative (to PATH_site) image filepath, output filename (written to)
2619 * @param string ImageMagick parameters
2620 * @param integer Optional, refers to which frame-number to select in the image. '' or 0
2621 * will select the first frame, 1 will select the next and so on...
2622 * @return string The result of a call to PHP function "exec()"
2624 function imageMagickExec($input, $output, $params, $frame = 0) {
2625 if (!$this->NO_IMAGE_MAGICK
) {
2627 // Unless noFramePrepended is set in the Install Tool, a frame number is added to
2628 // select a specific page of the image (by default this will be the first page)
2629 if (!$this->noFramePrepended
) {
2630 $frame = '[' . intval($frame) . ']';
2635 $cmd = t3lib_div
::imageMagickCommand('convert', $params . ' ' . $this->wrapFileName($input) . $frame . ' ' . $this->wrapFileName($output));
2636 $this->IM_commands
[] = array($output, $cmd);
2639 t3lib_div
::fixPermissions($output); // Change the permissions of the file
2646 * 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)
2647 * Can be used for many things, mostly scaling and effects.
2649 * @param string The relative (to PATH_site) image filepath, bottom file
2650 * @param string The relative (to PATH_site) image filepath, overlay file (top)
2651 * @param string The relative (to PATH_site) image filepath, the mask file (grayscale)
2652 * @param string The relative (to PATH_site) image filepath, output filename (written to)
2653 * @param [type] $handleNegation: ...
2656 function combineExec($input, $overlay, $mask, $output, $handleNegation = FALSE) {
2657 if (!$this->NO_IMAGE_MAGICK
) {
2658 $params = '-colorspace GRAY +matte';
2659 if ($handleNegation) {
2660 if ($this->maskNegate
) {
2661 $params .= ' ' . $this->maskNegate
;
2664 $theMask = $this->randomName() . '.' . $this->gifExtension
;
2665 $this->imageMagickExec($mask, $theMask, $params);
2666 $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
2667 $this->IM_commands
[] = array($output, $cmd);
2670 t3lib_div
::fixPermissions($output); // Change the permissions of the file
2672 if (is_file($theMask)) {
2681 * Escapes a file name so it can safely be used on the command line.
2683 * @param string $inputName filename to safeguard, must not be empty
2685 * @return string $inputName escaped as needed
2687 protected function wrapFileName($inputName) {
2688 return escapeshellarg($inputName);
2692 /***********************************
2694 * Various IO functions
2696 ***********************************/
2699 * Returns true if the input file existed
2701 * @param string Input file to check
2702 * @return string Returns the filename if the file existed, otherwise empty.
2704 function checkFile($file) {
2705 if (@is_file
($file)) {
2713 * Creates subdirectory in typo3temp/ if not already found.
2715 * @param string Name of sub directory
2716 * @return boolean Result of t3lib_div::mkdir(), true if it went well.
2718 function createTempSubDir($dirName) {
2720 // Checking if the this->tempPath is already prefixed with PATH_site and if not, prefix it with that constant.
2721 if (t3lib_div
::isFirstPartOfStr($this->tempPath
, PATH_site
)) {
2722 $tmpPath = $this->tempPath
;
2724 $tmpPath = PATH_site
. $this->tempPath
;
2727 // Making the temporary filename:
2728 if (!@is_dir
($tmpPath . $dirName)) {
2729 return t3lib_div
::mkdir($tmpPath . $dirName);
2734 * 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.
2736 * @param pointer The image pointer (reference)
2737 * @param string The ImageMagick parameters. Like effects, scaling etc.
2740 function applyImageMagickToPHPGif(&$im, $command) {
2741 $tmpStr = $this->randomName();
2742 $theFile = $tmpStr . '.' . $this->gifExtension
;
2743 $this->ImageWrite($im, $theFile);
2744 $this->imageMagickExec($theFile, $theFile, $command);
2745 $tmpImg = $this->imageCreateFromFile($theFile);
2749 $this->w
= imagesx($im);
2750 $this->h
= imagesy($im);
2752 if (!$this->dontUnlinkTempFiles
) {
2758 * 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.
2759 * For example: If the number of pixels exceeds $this->pixelLimitGif (normally 10000) then it will be a "jpg" string in return.
2761 * @param string The file extension, lowercase.
2762 * @param integer The width of the output image.
2763 * @param integer The height of the output image.
2764 * @return string The filename, either "jpg" or "gif"/"png" (whatever $this->gifExtension is set to.)
2766 function gif_or_jpg($type, $w, $h) {
2767 if ($type == 'ai' ||
$w * $h < $this->pixelLimitGif
) {
2768 return $this->gifExtension
;
2775 * Writing the internal image pointer, $this->im, to file based on the extension of the input filename
2776 * Used in GIFBUILDER
2777 * Uses $this->setup['reduceColors'] for gif/png images and $this->setup['quality'] for jpg images to reduce size/quality if needed.
2779 * @param string The filename to write to.
2780 * @return string Returns input filename
2781 * @see tslib_gifBuilder::gifBuild()
2783 function output($file) {
2786 preg_match('/([^\.]*)$/', $file, $reg);
2787 $ext = strtolower($reg[0]);
2791 if ($this->ImageWrite($this->im
, $file)) {
2792 // ImageMagick operations
2793 if ($this->setup
['reduceColors'] ||
!$this->png_truecolor
) {
2794 $reduced = $this->IMreduceColors($file, t3lib_div
::intInRange($this->setup
['reduceColors'], 256, $this->truecolorColors
, 256));
2796 @copy
($reduced, $file);
2800 t3lib_div
::gif_compress($file, 'IM'); // Compress with IM! (adds extra compression, LZW from ImageMagick) (Workaround for the absence of lzw-compression in GD)
2805 $quality = 0; // Use the default
2806 if ($this->setup
['quality']) {
2807 $quality = t3lib_div
::intInRange($this->setup
['quality'], 10, 100);
2809 if ($this->ImageWrite($this->im
, $file, $quality)) {
2814 $GLOBALS['TEMP_IMAGES_ON_PAGE'][] = $file;
2820 * Destroy internal image pointer, $this->im
2823 * @see tslib_gifBuilder::gifBuild()
2825 function destroy() {
2826 ImageDestroy($this->im
);
2830 * Returns Image Tag for input image information array.
2832 * @param array Image information array, key 0/1 is width/height and key 3 is the src value
2833 * @return string Image tag for the input image information array.
2835 function imgTag($imgInfo) {
2836 return '<img src="' . $imgInfo[3] . '" width="' . $imgInfo[0] . '" height="' . $imgInfo[1] . '" border="0" alt="" />';
2840 * Writes the input GDlib image pointer to file
2842 * @param pointer The GDlib image resource pointer
2843 * @param string The filename to write to
2844 * @param integer The image quality (for JPEGs)
2845 * @return boolean The output of either imageGif, imagePng or imageJpeg based on the filename to write
2846 * @see maskImageOntoImage(), scale(), output()
2848 function ImageWrite($destImg, $theImage, $quality = 0) {
2849 imageinterlace($destImg, 0);
2850 $ext = strtolower(substr($theImage, strrpos($theImage, '.') +
1));
2855 if (function_exists('imageJpeg')) {
2856 if ($quality == 0) {
2857 $quality = $this->jpegQuality
;
2859 $result = imageJpeg($destImg, $theImage, $quality);