Interim commit: This is fixes a bug in the getCachedImageDimensions() and cacheImageD...
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_stdgraphic.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 1999-2004 Kasper Skaarhoj (kasper@typo3.com)
6 * All rights reserved
7 *
8 * This script is part of the TYPO3 project. The TYPO3 project is
9 * free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * The GNU General Public License can be found at
15 * http://www.gnu.org/copyleft/gpl.html.
16 * A copy is found in the textfile GPL.txt and important notices to the license
17 * from the author is found in LICENSE.txt distributed with these scripts.
18 *
19 *
20 * This script is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
24 *
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
27 /**
28 * Standard graphical functions
29 *
30 * $Id$
31 * Revised for TYPO3 3.6 July/2003 by Kasper Skaarhoj
32 *
33 * @author Kasper Skaarhoj <kasper@typo3.com>
34 */
35 /**
36 * [CLASS/FUNCTION INDEX of SCRIPT]
37 *
38 *
39 *
40 * 143: class t3lib_stdGraphic
41 * 218: function init()
42 *
43 * SECTION: Layering images / "IMAGE" GIFBUILDER object
44 * 317: function maskImageOntoImage(&$im,$conf,$workArea)
45 * 377: function copyImageOntoImage(&$im,$conf,$workArea)
46 * 399: function copyGifOntoGif(&$im,$cpImg,$conf,$workArea)
47 * 478: function imagecopyresized(&$im, $cpImg, $Xstart, $Ystart, $cpImgCutX, $cpImgCutY, $w, $h, $w, $h)
48 *
49 * SECTION: Text / "TEXT" GIFBUILDER object
50 * 527: function makeText(&$im,$conf,$workArea)
51 * 643: function txtPosition($conf,$workArea,$BB)
52 * 697: function calcBBox($conf)
53 * 766: function addToMap($cords,$conf)
54 * 787: function calcTextCordsForMap($cords,$offset, $conf)
55 * 820: function SpacedImageTTFText(&$im, $fontSize, $angle, $x, $y, $Fcolor, $fontFile, $text, $spacing, $wordSpacing)
56 * 853: function fontResize($conf)
57 *
58 * SECTION: Other GIFBUILDER objects related to TEXT
59 * 915: function makeOutline(&$im,$conf,$workArea,$txtConf)
60 * 944: function circleOffset($distance, $iterations)
61 * 968: function makeEmboss(&$im,$conf,$workArea,$txtConf)
62 * 990: function makeShadow(&$im,$conf,$workArea,$txtConf)
63 *
64 * SECTION: Other GIFBUILDER objects
65 * 1120: function makeBox(&$im,$conf,$workArea)
66 * 1139: function makeEffect(&$im, $conf)
67 * 1154: function IMparams($setup)
68 * 1237: function adjust(&$im, $conf)
69 * 1269: function crop(&$im,$conf)
70 * 1299: function scale(&$im,$conf)
71 * 1331: function setWorkArea($workArea)
72 *
73 * SECTION: Adjustment functions
74 * 1372: function autolevels(&$im)
75 * 1403: function outputLevels(&$im,$low,$high,$swap='')
76 * 1435: function inputLevels(&$im,$low,$high,$swap='')
77 * 1466: function reduceColors(&$im,$limit, $cols)
78 *
79 * SECTION: GIFBUILDER Helper functions
80 * 1504: function prependAbsolutePath($fontFile)
81 * 1518: function v5_sharpen($factor)
82 * 1537: function v5_blur($factor)
83 * 1554: function randomName()
84 * 1566: function applyOffset($cords,$OFFSET)
85 * 1579: function convertColor($string)
86 * 1629: function recodeString($string)
87 * 1650: function singleChars($theText)
88 * 1673: function objPosition($conf,$workArea,$BB)
89 *
90 * SECTION: Scaling, Dimensions of images
91 * 1752: function imageMagickConvert($imagefile,$newExt='',$w='',$h='',$params='',$frame='',$options='',$mustCreate=0)
92 * 1835: function getImageDimensions($imageFile)
93 * 1863: function cacheImageDimensions($identifyResult)
94 * 1895: function getCachedImageDimensions($imageFile)
95 * 1930: function getImageScale($info,$w,$h,$options)
96 * 2018: function file_exists_typo3temp_file($output,$orig='')
97 *
98 * SECTION: ImageMagick API functions
99 * 2079: function imageMagickIdentify($imagefile)
100 * 2112: function imageMagickExec($input,$output,$params)
101 * 2130: function combineExec($input,$overlay,$mask,$output)
102 * 2145: function wrapFileName($inputName)
103 *
104 * SECTION: Various IO functions
105 * 2186: function checkFile($file)
106 * 2201: function applyImageMagickToPHPGif(&$im, $command)
107 * 2227: function gif_or_jpg($type,$w,$h)
108 * 2244: function output($file)
109 * 2288: function destroy()
110 * 2298: function imgTag ($imgInfo)
111 * 2310: function ImageGif($destImg, $theImage)
112 * 2327: function imageCreateFromGif($sourceImg)
113 *
114 * TOTAL FUNCTIONS: 54
115 * (This index is automatically created/updated by the extension "extdeveval")
116 *
117 */
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134 /**
135 * Class contains a bunch of cool functions for manipulating graphics with GDlib/Freetype and ImageMagick
136 * VERY OFTEN used with gifbuilder that extends this class and provides a TypoScript API to using these functions
137 *
138 * @author Kasper Skaarhoj <kasper@typo3.com>
139 * @package TYPO3
140 * @subpackage t3lib
141 * @see tslib_gifBuilder
142 */
143 class t3lib_stdGraphic {
144
145 // Internal configuration, set in init()
146 var $combineScript = 'combine'; // The ImageMagick filename used for combining two images. This name changed during the versions.
147 var $noFramePrepended=0; // If set, there is no frame pointer prepended to the filenames.
148 var $GD2=0; // Set, if the GDlib used is version 2.
149 var $gifExtension = 'gif'; // This should be changed to 'png' if you want this class to read/make PNG-files instead!
150 var $TTFLocaleConv = ''; // Used to recode input to TTF-functions for other charsets.
151 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.
152 var $imageMagickPath = ''; // path to imageMagick, eg: /usr/lib/
153 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!
154 var $webImageExt = 'gif,jpg,jpeg,png'; // Commalist of web image extensions (can be shown by a webbrowser)
155 var $maskNegate = ''; // Will be ' -negate' if ImageMagick ver 5.2+. See init();
156 var $NO_IM_EFFECTS = '';
157 var $cmds = Array (
158 'jpg' => '-colorspace RGB -sharpen 50 -quality 60',
159 'jpeg' => '-colorspace RGB -sharpen 50 -quality 60',
160 'gif' => '-colors 64',
161 'png' => '-colors 64'
162 );
163 var $NO_IMAGE_MAGICK = '';
164 var $V5_EFFECTS = 0;
165 var $mayScaleUp = 1;
166
167 // Variables for testing, alternative usage etc.
168 var $filenamePrefix=''; // Filename prefix for images scaled in imageMagickConvert()
169 var $imageMagickConvert_forceFileNameBody=''; // Forcing the output filename of imageMagickConvert() to this value. However after calling imageMagickConvert() it will be set blank again.
170 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.
171 var $dontCompress=0; // Prevents imageMagickConvert() from compressing the gif-files with t3lib_div::gif_compress()
172 var $dontUnlinkTempFiles=0; // For debugging ONLY!
173 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...
174
175 // Internal:
176 var $IM_commands = Array(); // All ImageMagick commands executed is stored in this array for tracking. Used by the Install Tools Image section
177 var $workArea = Array();
178
179 // Constants:
180 var $tempPath = 'typo3temp/'; // The temp-directory where to store the files. Relative to PATH_site.
181 var $scalecmd = '-geometry'; // ImageMagick scaling command; "-geometry" eller "-sample". Used in makeText() and imageMagickConvert()
182 var $im5fx_blurSteps='1x2,2x2,3x2,4x3,5x3,5x4,6x4,7x5,8x5,9x5'; // Used by v5_blur() to simulate 10 continuous steps of blurring
183 var $im5fx_sharpenSteps='1x2,2x2,3x2,2x3,3x3,4x3,3x4,4x4,4x5,5x5'; // Used by v5_sharpen() to simulate 10 continuous steps of sharpening.
184 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
185 var $colMap = Array ( // Array mapping HTML color names to RGB values.
186 'aqua' => Array(0,255,255),
187 'black' => Array(0,0,0),
188 'blue' => Array(0,0,255),
189 'fuchsia' => Array(255,0,255),
190 'gray' => Array(128,128,128),
191 'green' => Array(0,128,0),
192 'lime' => Array(0,255,0),
193 'maroon' => Array(128,0,0),
194 'navy' => Array(0,0,128),
195 'olive' => Array(128,128,0),
196 'purple' => Array(128,0,128),
197 'red' => Array(255,0,0),
198 'silver' => Array(192,192,192),
199 'teal' => Array(0,128,128),
200 'yellow' => Array(255,255,0),
201 'white' => Array(255,255,255)
202 );
203
204 // Charset conversion object:
205 var $csConvObj;
206 var $nativeCharset=''; // Is set to the native character set of the input strings.
207
208
209
210
211
212 /**
213 * Init function. Must always call this when using the class.
214 * This function will read the configuration information from $GLOBALS['TYPO3_CONF_VARS']['GFX'] can set some values in internal variables.
215 *
216 * @return void
217 */
218 function init() {
219 $gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX'];
220
221 if ($gfxConf['im_combine_filename']) $this->combineScript=$gfxConf['im_combine_filename'];
222 if ($gfxConf['im_noFramePrepended']) $this->noFramePrepended=1;
223
224 if ($gfxConf['gdlib_2']) {
225 $this->GD2=1;
226 }
227 if ($gfxConf['gdlib_png']) {
228 $this->gifExtension='png';
229 }
230 if ($gfxConf['TTFLocaleConv']) {
231 $this->TTFLocaleConv = $gfxConf['TTFLocaleConv'];
232 }
233 if ($gfxConf['enable_typo3temp_db_tracking']) {
234 $this->enable_typo3temp_db_tracking = $gfxConf['enable_typo3temp_db_tracking'];
235 }
236
237 $this->imageMagickPath = $gfxConf['im_path'];
238 $this->imageFileExt = $gfxConf['imagefile_ext'];
239
240 // This should be set if ImageMagick ver. 5+ is used.
241 if ($gfxConf['im_negate_mask']) {
242 // Boolean. Indicates if the mask images should be inverted first.
243 // This depends of the ImageMagick version. Below ver. 5.1 this should be false.
244 // Above ImageMagick version 5.2+ it should be true.
245 // Just set the flag if the masks works opposite the intension!
246 $this->maskNegate = ' -negate';
247 }
248 if ($gfxConf['im_no_effects']) {
249 // Boolean. This is necessary if using ImageMagick 5+.
250 // Approved version for using effects is version 4.2.9.
251 // Effects in Imagemagick 5+ tends to render very slowly!!
252 // - therefore must be disabled in order not to perform sharpen, blurring and such.
253 $this->NO_IM_EFFECTS = 1;
254
255 $this->cmds['jpg'] = '-colorspace RGB -quality 60';
256 $this->cmds['jpeg'] = '-colorspace RGB -quality 60';
257 }
258 // ... but if 'im_v5effects' is set, dont care about 'im_no_effects'
259 if ($gfxConf['im_v5effects']) {
260 $this->NO_IM_EFFECTS = 0;
261 $this->V5_EFFECTS = 1;
262
263 if ($gfxConf['im_v5effects']>0) {
264 $this->cmds['jpg'] = '-colorspace RGB -quality 60'.$this->v5_sharpen(10);
265 $this->cmds['jpeg'] = '-colorspace RGB -quality 60'.$this->v5_sharpen(10);
266 }
267 }
268
269 if (!$gfxConf['im']) {
270 $this->NO_IMAGE_MAGICK = 1;
271 }
272 // Secures that images are not scaled up.
273 if ($gfxConf['im_noScaleUp']) {
274 $this->mayScaleUp=0;
275 }
276
277 if (TYPO3_MODE=='FE') {
278 $this->csConvObj = &$GLOBALS['TSFE']->csConvObj;
279 } else { // BE assumed:
280 $this->csConvObj = &$GLOBALS['LANG']->csConvObj;
281 }
282 $this->nativeCharset = $GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'];
283 }
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300 /*************************************************
301 *
302 * Layering images / "IMAGE" GIFBUILDER object
303 *
304 *************************************************/
305
306 /**
307 * Implements the "IMAGE" GIFBUILDER object, when the "mask" property is true.
308 * 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
309 * The operation involves ImageMagick for combining.
310 *
311 * @param pointer GDlib image pointer
312 * @param array TypoScript array with configuration for the GIFBUILDER object.
313 * @param array The current working area coordinates.
314 * @return void
315 * @see tslib_gifBuilder::make()
316 */
317 function maskImageOntoImage(&$im,$conf,$workArea) {
318 if ($conf['file'] && $conf['mask']) {
319 $BBimage = $this->imageMagickConvert($conf['file'],$this->gifExtension,'','','','','');
320 $BBmask = $this->imageMagickConvert($conf['mask'],$this->gifExtension,'','','','','');
321 if ($BBimage && $BBmask) {
322 $w = imagesx($im);
323 $h = imagesy($im);
324 $tmpStr = $this->randomName();
325 $theImage = $tmpStr.'_img.'.$this->gifExtension;
326 $theDest = $tmpStr.'_dest.'.$this->gifExtension;
327 $theMask = $tmpStr.'_mask.'.$this->gifExtension;
328 $theMask2 = $tmpStr.'_mask2.'.trim($GLOBALS['TYPO3_CONF_VARS']['GFX']['im_mask_temp_ext_noloss']);
329 // prepare overlay image
330 $cpImg = $this->imageCreateFromGif($BBimage[3]);
331 $destImg = imagecreate($w,$h);
332 ImageColorAllocate($destImg, 0,0,0);
333 $this->copyGifOntoGif($destImg,$cpImg,$conf,$workArea);
334 $this->ImageGif($destImg, $theImage);
335 imageDestroy($cpImg);
336 imageDestroy($destImg);
337 // prepare mask image
338 $cpImg = $this->imageCreateFromGif($BBmask[3]);
339 $destImg = imagecreate($w,$h);
340 ImageColorAllocate($destImg, 0,0,0);
341 $this->copyGifOntoGif($destImg,$cpImg,$conf,$workArea);
342 $this->ImageGif($destImg, $theMask);
343 imageDestroy($cpImg);
344 imageDestroy($destImg);
345 // treat the mask
346 $this->imageMagickExec($theMask,$theMask2,'-colorspace GRAY'.$this->maskNegate);
347 // mask the images
348 $this->ImageGif($im, $theDest);
349
350 $this->combineExec($theDest,$theImage,$theMask2,$theDest);
351
352 $backIm = $this->imageCreateFromGif($theDest); // The main image is loaded again...
353 if ($backIm) { // ... and if nothing went wrong we load it onto the old one.
354 ImageColorTransparent($backIm,-1);
355 $im = $backIm;
356 }
357 // unlink files from process
358 if (!$this->dontUnlinkTempFiles) {
359 unlink($theDest);
360 unlink($theImage);
361 unlink($theMask);
362 unlink($theMask2);
363 }
364 }
365 }
366 }
367
368 /**
369 * Implements the "IMAGE" GIFBUILDER object, when the "mask" property is false (using only $conf['file'])
370 *
371 * @param pointer GDlib image pointer
372 * @param array TypoScript array with configuration for the GIFBUILDER object.
373 * @param array The current working area coordinates.
374 * @return void
375 * @see tslib_gifBuilder::make(), maskImageOntoImage()
376 */
377 function copyImageOntoImage(&$im,$conf,$workArea) {
378 if ($conf['file']) {
379 if ($conf['BBOX'][2]!=$this->gifExtension) {
380 $conf['BBOX']=$this->imageMagickConvert($conf['BBOX'][3],$this->gifExtension,'','','','','');
381 $conf['file']=$conf['BBOX'][3];
382 }
383 $cpImg = $this->imageCreateFromGif($conf['file']);
384 $this->copyGifOntoGif($im,$cpImg,$conf,$workArea);
385 imageDestroy($cpImg);
386 }
387 }
388
389 /**
390 * Copies two GDlib image pointers onto each other, using TypoScript configuration from $conf and the input $workArea definition.
391 *
392 * @param pointer GDlib image pointer, destination (bottom image)
393 * @param pointer GDlib image pointer, source (top image)
394 * @param array TypoScript array with the properties for the IMAGE GIFBUILDER object. Only used for the "tile" property value.
395 * @param array Work area
396 * @return void Works on the $im image pointer
397 * @access private
398 */
399 function copyGifOntoGif(&$im,$cpImg,$conf,$workArea) {
400 $cpW = imagesx($cpImg);
401 $cpH = imagesy($cpImg);
402 $tile = t3lib_div::intExplode(',',$conf['tile']);
403 $tile[0] = t3lib_div::intInRange($tile[0],1,20);
404 $tile[1] = t3lib_div::intInRange($tile[1],1,20);
405 $cpOff = $this->objPosition($conf,$workArea,Array($cpW*$tile[0],$cpH*$tile[1]));
406
407 for ($xt=0;$xt<$tile[0];$xt++) {
408 $Xstart=$cpOff[0]+$cpW*$xt;
409 if ($Xstart+$cpW > $workArea[0]) { // if this image is inside of the workArea, then go on
410 // X:
411 if ($Xstart < $workArea[0]) {
412 $cpImgCutX = $workArea[0]-$Xstart;
413 $Xstart = $workArea[0];
414 } else {
415 $cpImgCutX = 0;
416 }
417 $w = $cpW-$cpImgCutX;
418 if ($Xstart > $workArea[0]+$workArea[2]-$w) {
419 $w = $workArea[0]+$workArea[2]-$Xstart;
420 }
421 if ($Xstart < $workArea[0]+$workArea[2]) { // if this image is inside of the workArea, then go on
422 // Y:
423 for ($yt=0;$yt<$tile[1];$yt++) {
424 $Ystart=$cpOff[1]+$cpH*$yt;
425 if ($Ystart+$cpH > $workArea[1]) { // if this image is inside of the workArea, then go on
426 if ($Ystart < $workArea[1]) {
427 $cpImgCutY = $workArea[1]-$Ystart;
428 $Ystart = $workArea[1];
429 } else {
430 $cpImgCutY = 0;
431 }
432 $h = $cpH-$cpImgCutY;
433 if ($Ystart > $workArea[1]+$workArea[3]-$h) {
434 $h = $workArea[1]+$workArea[3]-$Ystart;
435 }
436 if ($Ystart < $workArea[1]+$workArea[3]) { // if this image is inside of the workArea, then go on
437 $this->imagecopyresized($im, $cpImg, $Xstart, $Ystart, $cpImgCutX, $cpImgCutY, $w, $h, $w, $h);
438 }
439 }
440 } // Y:
441 }
442 }
443 }
444 }
445
446 /**
447 * Alternative function for using the similat PHP function imagecopyresized(). Used for GD2 only.
448 *
449 * OK, the reason for this stupid fix is the following story:
450 * GD1.x was capable of copying two images together and combining their palettes! GD2 is apparently not.
451 * With GD2 only the palette of the dest-image is used which mostly results in totally black images when trying to
452 * copy a color-ful image onto the destination.
453 * The GD2-fix is to
454 * 1) Create a blank TRUE-COLOR image
455 * 2) Copy the destination image onto that one
456 * 3) Then do the actual operation; Copying the source (top image) onto that
457 * 4) ... and return the result pointer.
458 * 5) Reduce colors (if we do not, the result may become strange!)
459 * It works, but the resulting images is now a true-color PNG which may be very large.
460 * So, why not use 'imagetruecolortopalette ($im, TRUE, 256)' - well because it does NOT WORK! So simple is that.
461 *
462 * For parameters, see PHP function "imagecopyresized()"
463 *
464 * @param pointer see PHP function "imagecopyresized()"
465 * @param pointer see PHP function "imagecopyresized()"
466 * @param integer see PHP function "imagecopyresized()"
467 * @param integer see PHP function "imagecopyresized()"
468 * @param integer see PHP function "imagecopyresized()"
469 * @param integer see PHP function "imagecopyresized()"
470 * @param integer see PHP function "imagecopyresized()"
471 * @param integer see PHP function "imagecopyresized()"
472 * @param integer see PHP function "imagecopyresized()"
473 * @param integer see PHP function "imagecopyresized()"
474 * @return void
475 * @access private
476 * @see t3lib_iconWorks::imagecopyresized()
477 */
478 function imagecopyresized(&$im, $cpImg, $Xstart, $Ystart, $cpImgCutX, $cpImgCutY, $w, $h, $w, $h) {
479 if ($this->GD2) {
480 $im_base = imagecreatetruecolor(imagesx($im), imagesy($im)); // Make true color image
481 imagecopyresized($im_base, $im, 0,0,0,0, imagesx($im),imagesy($im),imagesx($im),imagesy($im)); // Copy the source image onto that
482 imagecopyresized($im_base, $cpImg, $Xstart, $Ystart, $cpImgCutX, $cpImgCutY, $w, $h, $w, $h); // Then copy the $cpImg onto that (the actual operation!)
483 $im = $im_base; // Set pointer
484 $this->makeEffect($im, Array('value'=>'colors=256')); // Reduce colors to 256 - make SURE that IM is working then!
485 } else {
486 imagecopyresized($im, $cpImg, $Xstart, $Ystart, $cpImgCutX, $cpImgCutY, $w, $h, $w, $h);
487 }
488 }
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512 /********************************
513 *
514 * Text / "TEXT" GIFBUILDER object
515 *
516 ********************************/
517
518 /**
519 * Implements the "TEXT" GIFBUILDER object
520 *
521 * @param pointer GDlib image pointer
522 * @param array TypoScript array with configuration for the GIFBUILDER object.
523 * @param array The current working area coordinates.
524 * @return void
525 * @see tslib_gifBuilder::make()
526 */
527 function makeText(&$im,$conf,$workArea) {
528 // Spacing
529 $spacing = intval($conf['spacing']);
530 $wordSpacing = intval($conf['wordSpacing']);
531 $wordSpacing = $wordSpacing?$wordSpacing:$spacing*2;
532 // Position
533 $txtPos = $this->txtPosition($conf,$workArea,$conf['BBOX']);
534 $theText = $this->recodeString($conf['text']);
535
536 if ($conf['imgMap'] && is_array($conf['imgMap.'])) {
537 $this->addToMap($this->calcTextCordsForMap($conf['BBOX'][2],$txtPos, $conf['imgMap.']), $conf['imgMap.']);
538 }
539 if (!$conf['hideButCreateMap']) {
540 // Font Color:
541 $cols=$this->convertColor($conf['fontColor']);
542 // NiceText is calculated
543 if (!$conf['niceText']) {
544 // Font Color is reserved:
545 $this->reduceColors($im,256, 200);
546 $Fcolor = ImageColorAllocate($im, $cols[0],$cols[1],$cols[2]);
547 // antiAliasing is setup:
548 $Fcolor = ($conf['antiAlias']) ? $Fcolor : -$Fcolor;
549
550 for ($a=0; $a<$conf['iterations']; $a++) {
551 if ($spacing || $wordSpacing) { // If any kind of spacing applys, we use this function:
552 $this->SpacedImageTTFText($im, $conf['fontSize'], $conf['angle'], $txtPos[0], $txtPos[1], $Fcolor, t3lib_stdGraphic::prependAbsolutePath($conf['fontFile']), $theText, $spacing, $wordSpacing);
553 } else {
554 ImageTTFText($im, t3lib_div::freetypeDpiComp($conf['fontSize']), $conf['angle'], $txtPos[0], $txtPos[1], $Fcolor, t3lib_stdGraphic::prependAbsolutePath($conf['fontFile']), $theText);
555 }
556 }
557 } else { // NICETEXT::
558 // options anti_aliased and iterations is NOT available when doing this!!
559 $w = imagesx($im);
560 $h = imagesy($im);
561 $tmpStr = $this->randomName();
562
563 $fileMenu = $tmpStr.'_menuNT.'.$this->gifExtension;
564 $fileColor = $tmpStr.'_colorNT.'.$this->gifExtension;
565 $fileMask = $tmpStr.'_maskNT.'.$this->gifExtension;
566 // Scalefactor
567 $sF = t3lib_div::intInRange($conf['niceText.']['scaleFactor'],2,5);
568 $newW = ceil($sF*imagesx($im));
569 $newH = ceil($sF*imagesy($im));
570
571 // Make mask
572 $maskImg = imagecreate($newW, $newH);
573 ImageColorAllocate($maskImg, 255,255,255);
574 $Fcolor = ImageColorAllocate($maskImg, 0,0,0);
575 if ($spacing || $wordSpacing) { // If any kind of spacing applys, we use this function:
576 $this->SpacedImageTTFText($maskImg, ceil($sF*$conf['fontSize']), $conf['angle'], ceil($sF*$txtPos[0]), ceil($sF*$txtPos[1]), $Fcolor, t3lib_stdGraphic::prependAbsolutePath($conf['fontFile']), $theText, ceil($sF*$spacing), ceil($sF*$wordSpacing));
577 } else {
578 ImageTTFText($maskImg, t3lib_div::freetypeDpiComp(ceil($sF*$conf['fontSize'])), $conf['angle'], ceil($sF*$txtPos[0]), ceil($sF*$txtPos[1]), $Fcolor, t3lib_stdGraphic::prependAbsolutePath($conf['fontFile']), $theText);
579 }
580 $this->ImageGif($maskImg, $fileMask);
581 ImageDestroy($maskImg);
582
583 // Downscales the mask
584 if ($this->NO_IM_EFFECTS) {
585 if ($this->maskNegate) {
586 $command = trim($this->scalecmd.' '.$w.'x'.$h.'!'); // Negate 2 times makes no negate...
587 } else {
588 $command = trim($this->scalecmd.' '.$w.'x'.$h.'! -negate');
589 }
590 } else {
591 if ($this->maskNegate) {
592 $command = trim($conf['niceText.']['before'].' '.$this->scalecmd.' '.$w.'x'.$h.'! '.$conf['niceText.']['after']);
593 } else {
594 $command = trim($conf['niceText.']['before'].' '.$this->scalecmd.' '.$w.'x'.$h.'! '.$conf['niceText.']['after'].' -negate');
595 }
596 if ($conf['niceText.']['sharpen']) {
597 if ($this->V5_EFFECTS) {
598 $command.=$this->v5_sharpen($conf['niceText.']['sharpen']);
599 } else {
600 $command.=' -sharpen '.t3lib_div::intInRange($conf['niceText.']['sharpen'],1,99);
601 }
602 }
603 }
604 $this->imageMagickExec($fileMask,$fileMask,$command);
605
606 // Make the color-file
607 $colorImg = imagecreate($w,$h);
608 ImageColorAllocate($colorImg, $cols[0],$cols[1],$cols[2]);
609 $this->ImageGif($colorImg, $fileColor);
610 ImageDestroy($colorImg);
611
612 // The mask is applied
613 $this->ImageGif($im, $fileMenu); // The main pictures is saved temporarily
614
615 $this->combineExec($fileMenu,$fileColor,$fileMask,$fileMenu);
616
617 $backIm = $this->imageCreateFromGif($fileMenu); // The main image is loaded again...
618 if ($backIm) { // ... and if nothing went wrong we load it onto the old one.
619 ImageColorTransparent($backIm,-1);
620 $im = $backIm;
621 }
622
623 // Deleting temporary files;
624 if (!$this->dontUnlinkTempFiles) {
625 unlink($fileMenu);
626 unlink($fileColor);
627 unlink($fileMask);
628 }
629 }
630 }
631 }
632
633 /**
634 * Calculates text position for printing the text onto the image based on configuration like alignment and workarea.
635 *
636 * @param array TypoScript array for the TEXT GIFBUILDER object
637 * @param array Workarea definition
638 * @param array Bounding box information, was set in tslib_gifBuilder::start()
639 * @return array [0]=x, [1]=y, [2]=w, [3]=h
640 * @access private
641 * @see makeText()
642 */
643 function txtPosition($conf,$workArea,$BB) {
644 $bbox = $BB[2];
645 $angle=intval($conf['angle'])/180*pi();
646 $conf['angle']=0;
647 $straightBB = $this->calcBBox($conf);
648
649 // offset, align, valign, workarea
650 $result=Array(); // [0]=x, [1]=y, [2]=w, [3]=h
651 $result[2] = $BB[0];
652 $result[3] = $BB[1];
653 $w=$workArea[2];
654 $h=$workArea[3];
655
656 switch($conf['align']) {
657 case 'right':
658 case 'center':
659 $factor=abs(cos($angle));
660 $sign=(cos($angle)<0)?-1:1;
661 $len1 = $sign*$factor*$straightBB[0];
662 $len2= $sign*$BB[0];
663 $result[0] = $w-ceil($len2*$factor+(1-$factor)*$len1);
664
665 $factor=abs(sin($angle));
666 $sign=(sin($angle)<0)?-1:1;
667 $len1= $sign*$factor*$straightBB[0];
668 $len2= $sign*$BB[1];
669 $result[1]=ceil($len2*$factor+(1-$factor)*$len1);
670 break;
671 }
672 switch($conf['align']) {
673 case 'right':
674 break;
675 case 'center':
676 $result[0] = round(($result[0])/2);
677 $result[1] = round(($result[1])/2);
678 break;
679 default:
680 $result[0]=0;
681 $result[1]=0;
682 break;
683 }
684 $result = $this->applyOffset($result,t3lib_div::intExplode(',',$conf['offset']));
685 $result = $this->applyOffset($result,$workArea);
686 return $result;
687 }
688
689 /**
690 * Calculates bounding box information for the TEXT GIFBUILDER object.
691 *
692 * @param array TypoScript array for the TEXT GIFBUILDER object
693 * @return array Array with three keys [0]/[1] being x/y and [2] being the bounding box array
694 * @access private
695 * @see txtPosition(), tslib_gifBuilder::start()
696 */
697 function calcBBox($conf) {
698 if (!$conf['niceText']) {
699 $sF = 1;
700 } else { // NICETEXT::
701 $sF = t3lib_div::intInRange($conf['niceText.']['scaleFactor'],2,5);
702 }
703
704 $spacing = intval($conf['spacing']);
705 $wordSpacing = intval($conf['wordSpacing']);
706 $wordSpacing = $wordSpacing?$wordSpacing:$spacing*2;
707
708 $spacing*=$sF;
709 $wordSpacing*=$sF;
710 $theText = $this->recodeString($conf['text']);
711
712 $charInf = ImageTTFBBox(t3lib_div::freetypeDpiComp($sF*$conf['fontSize']), $conf['angle'], t3lib_stdGraphic::prependAbsolutePath($conf['fontFile']), $theText);
713 $theBBoxInfo = $charInf;
714 if ($conf['angle']) {
715 $xArr = Array($charInf[0],$charInf[2],$charInf[4],$charInf[6]);
716 $yArr = Array($charInf[1],$charInf[3],$charInf[5],$charInf[7]);
717 $x=max($xArr)-min($xArr);
718 $y=max($yArr)-min($yArr);
719 } else {
720 $x = ($charInf[2]-$charInf[0]);
721 $y = ($charInf[1]-$charInf[7]);
722 }
723 if ($spacing || $wordSpacing) { // If any kind of spacing applys, we use this function:
724 $x=0;
725 if (!$spacing && $wordSpacing) {
726 $bits = explode(' ',$theText);
727 while(list(,$word)=each($bits)) {
728 $word.=' ';
729 $wordInf = ImageTTFBBox(t3lib_div::freetypeDpiComp($sF*$conf['fontSize']), $conf['angle'], t3lib_stdGraphic::prependAbsolutePath($conf['fontFile']), $word);
730 $wordW = ($wordInf[2]-$wordInf[0]);
731 $x+=$wordW+$wordSpacing;
732 }
733 } else {
734 $utf8Chars = $this->singleChars($theText);
735 // For each UTF-8 char, do:
736 foreach($utf8Chars as $char) {
737 $charInf = ImageTTFBBox(t3lib_div::freetypeDpiComp($sF*$conf['fontSize']), $conf['angle'], t3lib_stdGraphic::prependAbsolutePath($conf['fontFile']), $char);
738 $charW = ($charInf[2]-$charInf[0]);
739 $x+=$charW+(($char==' ')?$wordSpacing:$spacing);
740 }
741 }
742 }
743
744 if ($sF>1) {
745 $x = ceil($x/$sF);
746 $y = ceil($y/$sF);
747 if (is_array($theBBoxInfo)) {
748 reset($theBBoxInfo);
749 while(list($key,$val)=each($theBBoxInfo)) {
750 $theBBoxInfo[$key]=ceil($theBBoxInfo[$key]/$sF);
751 }
752 }
753 }
754 return Array($x,$y,$theBBoxInfo);
755 }
756
757 /**
758 * Adds an <area> tag to the internal variable $this->map which is used to accumulate the content for an ImageMap
759 *
760 * @param array Coordinates for a polygon image map as created by ->calcTextCordsForMap()
761 * @param array Configuration for "imgMap." property of a TEXT GIFBUILDER object.
762 * @return void
763 * @access private
764 * @see makeText(), calcTextCordsForMap()
765 */
766 function addToMap($cords,$conf) {
767 $JS = $conf['noBlur'] ? '' : ' onfocus="blurLink(this);"';
768 $this->map.='<area'.
769 ' shape="poly"'.
770 ' coords="'.implode($cords,',').'"'.
771 ' href="'.htmlspecialchars($conf['url']).'"'.
772 ($conf['target'] ? ' target="'.$conf['target'].'"' : '').
773 $JS.
774 ' alt="" />';
775 }
776
777 /**
778 * Calculating the coordinates for a TEXT string on an image map. Used in an <area> tag
779 *
780 * @param array Coordinates (from BBOX array)
781 * @param array Offset array
782 * @param array Configuration for "imgMap." property of a TEXT GIFBUILDER object.
783 * @return array
784 * @access private
785 * @see makeText(), calcTextCordsForMap()
786 */
787 function calcTextCordsForMap($cords,$offset, $conf) {
788 $pars = t3lib_div::intExplode(',',$conf['explode'].',');
789
790 $newCords[0] = $cords[0]+$offset[0]-$pars[0];
791 $newCords[1] = $cords[1]+$offset[1]+$pars[1];
792 $newCords[2] = $cords[2]+$offset[0]+$pars[0];
793 $newCords[3] = $cords[3]+$offset[1]+$pars[1];
794 $newCords[4] = $cords[4]+$offset[0]+$pars[0];
795 $newCords[5] = $cords[5]+$offset[1]-$pars[1];
796 $newCords[6] = $cords[6]+$offset[0]-$pars[0];
797 $newCords[7] = $cords[7]+$offset[1]-$pars[1];
798
799 return $newCords;
800 }
801
802 /**
803 * Printing text onto an image like the PHP function imageTTFText does but in addition it offers options for spacing of letters and words.
804 * Spacing is done by printing one char at a time and this means that the spacing is rather uneven and probably not very nice.
805 * See
806 *
807 * @param pointer (See argument for PHP function imageTTFtext())
808 * @param integer (See argument for PHP function imageTTFtext())
809 * @param integer (See argument for PHP function imageTTFtext())
810 * @param integer (See argument for PHP function imageTTFtext())
811 * @param integer (See argument for PHP function imageTTFtext())
812 * @param integer (See argument for PHP function imageTTFtext())
813 * @param string (See argument for PHP function imageTTFtext())
814 * @param string (See argument for PHP function imageTTFtext()). UTF-8 string, possibly with entities in.
815 * @param integer The spacing of letters in pixels
816 * @param integer The spacing of words in pixels
817 * @return void
818 * @access private
819 */
820 function SpacedImageTTFText(&$im, $fontSize, $angle, $x, $y, $Fcolor, $fontFile, $text, $spacing, $wordSpacing) {
821 if (!$spacing && $wordSpacing) {
822 $bits = explode(' ',$text);
823 reset($bits);
824 while(list(,$word)=each($bits)) {
825 $word.=' ';
826 $word = $word;
827 $wordInf = ImageTTFBBox(t3lib_div::freetypeDpiComp($fontSize), $angle, t3lib_stdGraphic::prependAbsolutePath($fontFile), $word);
828 $wordW = ($wordInf[2]-$wordInf[0]);
829 ImageTTFText($im, t3lib_div::freetypeDpiComp($fontSize), $angle, $x, $y, $Fcolor, t3lib_stdGraphic::prependAbsolutePath($fontFile), $word);
830 $x+=$wordW+$wordSpacing;
831 }
832 } else {
833 $utf8Chars = $this->singleChars($text);
834 // For each UTF-8 char, do:
835 foreach($utf8Chars as $char) {
836 $charInf = ImageTTFBBox(t3lib_div::freetypeDpiComp($fontSize), $angle, t3lib_stdGraphic::prependAbsolutePath($fontFile), $char);
837 $charW = ($charInf[2]-$charInf[0]);
838 ImageTTFText($im, t3lib_div::freetypeDpiComp($fontSize), $angle, $x, $y, $Fcolor, t3lib_stdGraphic::prependAbsolutePath($fontFile), $char);
839 $x+=$charW+(($char==' ')?$wordSpacing:$spacing);
840 }
841 }
842 }
843
844 /**
845 * Function that finds the right fontsize that will render the textstring within a certain width
846 *
847 * @param array The TypoScript properties of the TEXT GIFBUILDER object
848 * @return integer The new fontSize
849 * @access private
850 * @author Rene Fritz <r.fritz@colorcube.de>
851 * @see tslib_gifBuilder::start()
852 */
853 function fontResize($conf) {
854 // 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!!!!
855 $maxWidth = intval($conf['maxWidth']);
856 if ($maxWidth) {
857 if ($spacing || $wordSpacing) { // If any kind of spacing applys, we use this function:
858 return $conf['fontSize'];
859 // ################ no calc for spacing yet !!!!!!
860 } else {
861 $fontSize = $conf['fontSize'];
862 do {
863 $conf['fontSize'] = $fontSize;
864 // determine bounding box.
865 $bounds = ImageTTFBBox(t3lib_div::freetypeDpiComp($conf['fontSize']), $conf['angle'], t3lib_stdGraphic::prependAbsolutePath($conf['fontFile']), $this->recodeString($conf['text']));
866 if ($conf['angle']< 0) {
867 $pixelWidth = abs($bounds[4]-$bounds[0]);
868 } elseif ($conf['angle'] > 0) {
869 $pixelWidth = abs($bounds[2]-$bounds[6]);
870 } else {
871 $pixelWidth = abs($bounds[4]-$bounds[6]);
872 }
873 // This is a very raw calculation but it makes it in one step
874 $fontSize=(int)($maxWidth*$fontSize/$pixelWidth);
875 if ($fontSize >= $conf['fontSize']) {
876 $fontSize = $conf['fontSize']-1;
877 }
878 } while ($pixelWidth > $maxWidth);
879 }//if spacing
880 }
881 return $conf['fontSize'];
882 }
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899 /*********************************************
900 *
901 * Other GIFBUILDER objects related to TEXT
902 *
903 *********************************************/
904
905 /**
906 * Implements the "OUTLINE" GIFBUILDER object / property for the TEXT object
907 *
908 * @param pointer GDlib image pointer
909 * @param array TypoScript array with configuration for the GIFBUILDER object.
910 * @param array The current working area coordinates.
911 * @param array TypoScript array with configuration for the associated TEXT GIFBUILDER object.
912 * @return void
913 * @see tslib_gifBuilder::make(), makeText()
914 */
915 function makeOutline(&$im,$conf,$workArea,$txtConf) {
916 $thickness = intval($conf['thickness']);
917 if ($thickness) {
918 $txtConf['fontColor'] = $conf['color'];
919 $outLineDist = t3lib_div::intInRange($thickness,1,2);
920 for ($b=1;$b<=$outLineDist;$b++) {
921 if ($b==1) {
922 $it = 8;
923 } else {
924 $it = 16;
925 }
926 $outL = $this->circleOffset($b, $it);
927 for ($a=0;$a<$it;$a++) {
928 $this->makeText($im,$txtConf,$this->applyOffset($workArea,$outL[$a]));
929 }
930 }
931 }
932 }
933
934 /**
935 * Creates some offset values in an array used to simulate a circularly applied outline around TEXT
936 *
937 * access private
938 *
939 * @param integer Distance
940 * @param integer Iterations.
941 * @return array
942 * @see makeOutline()
943 */
944 function circleOffset($distance, $iterations) {
945 $res = Array();
946 if ($distance && $iterations) {
947 for ($a=0;$a<$iterations;$a++) {
948 $yOff = round(sin(2*pi()/$iterations*($a+1))*100*$distance);
949 if ($yOff) {$yOff = intval(ceil(abs($yOff/100))*($yOff/abs($yOff)));}
950 $xOff = round(cos(2*pi()/$iterations*($a+1))*100*$distance);
951 if ($xOff) {$xOff = intval(ceil(abs($xOff/100))*($xOff/abs($xOff)));}
952 $res[$a] = Array($xOff,$yOff);
953 }
954 }
955 return $res;
956 }
957
958 /**
959 * Implements the "EMBOSS" GIFBUILDER object / property for the TEXT object
960 *
961 * @param pointer GDlib image pointer
962 * @param array TypoScript array with configuration for the GIFBUILDER object.
963 * @param array The current working area coordinates.
964 * @param array TypoScript array with configuration for the associated TEXT GIFBUILDER object.
965 * @return void
966 * @see tslib_gifBuilder::make(), makeShadow()
967 */
968 function makeEmboss(&$im,$conf,$workArea,$txtConf) {
969 $conf['color']=$conf['highColor'];
970 $this->makeShadow($im,$conf,$workArea,$txtConf);
971 $newOffset = t3lib_div::intExplode(',',$conf['offset']);
972 $newOffset[0]*=-1;
973 $newOffset[1]*=-1;
974 $conf['offset']=implode($newOffset,',');
975 $conf['color']=$conf['lowColor'];
976 $this->makeShadow($im,$conf,$workArea,$txtConf);
977 }
978
979 /**
980 * Implements the "SHADOW" GIFBUILDER object / property for the TEXT object
981 * The operation involves ImageMagick for combining.
982 *
983 * @param pointer GDlib image pointer
984 * @param array TypoScript array with configuration for the GIFBUILDER object.
985 * @param array The current working area coordinates.
986 * @param array TypoScript array with configuration for the associated TEXT GIFBUILDER object.
987 * @return void
988 * @see tslib_gifBuilder::make(), makeText(), makeEmboss()
989 */
990 function makeShadow(&$im,$conf,$workArea,$txtConf) {
991 $workArea = $this->applyOffset($workArea,t3lib_div::intExplode(',',$conf['offset']));
992 $blurRate = t3lib_div::intInRange(intval($conf['blur']),0,99);
993
994 if (!$blurRate || $this->NO_IM_EFFECTS) { // No effects if ImageMagick ver. 5+
995 $txtConf['fontColor'] = $conf['color'];
996 $this->makeText($im,$txtConf,$workArea);
997 } else {
998 $w = imagesx($im);
999 $h = imagesy($im);
1000 $blurBorder= 3; // area around the blur used for cropping something
1001 $tmpStr = $this->randomName();
1002 $fileMenu = $tmpStr.'_menu.'.$this->gifExtension;
1003 $fileColor = $tmpStr.'_color.'.$this->gifExtension;
1004 $fileMask = $tmpStr.'_mask.'.$this->gifExtension;
1005
1006 // BlurColor Image laves
1007 $blurColImg = imagecreate($w,$h);
1008 $bcols=$this->convertColor($conf['color']);
1009 ImageColorAllocate($blurColImg, $bcols[0],$bcols[1],$bcols[2]);
1010 $this->ImageGif($blurColImg, $fileColor);
1011 ImageDestroy($blurColImg);
1012
1013 // The mask is made: BlurTextImage
1014 $blurTextImg = imagecreate($w+$blurBorder*2,$h+$blurBorder*2);
1015 ImageColorAllocate($blurTextImg, 0,0,0); // black background
1016 $txtConf['fontColor'] = 'white';
1017 $blurBordArr = Array($blurBorder,$blurBorder);
1018 $this->makeText($blurTextImg,$txtConf, $this->applyOffset($workArea,$blurBordArr));
1019 $this->ImageGif($blurTextImg, $fileMask); // dump to temporary file
1020 ImageDestroy($blurTextImg); // destroy
1021
1022
1023 $command='';
1024 $command.=$this->maskNegate;
1025
1026 if ($this->V5_EFFECTS) {
1027 $command.=$this->v5_blur($blurRate+1);
1028 } else {
1029 // Blurring of the mask
1030 $times = ceil($blurRate/10); // How many blur-commands that is executed. Min = 1;
1031 $newBlurRate = $blurRate*4; // Her booster vi blur-rate, så at den allerede ved 25 er på 100. Resten op til 99 går på iterationer af blur-kommandoen
1032 $newBlurRate = t3lib_div::intInRange($newBlurRate,1,99);
1033 for ($a=0;$a<$times;$a++) { // Building blur-command
1034 $command.=' -blur '.$blurRate;
1035 }
1036 }
1037
1038 $this->imageMagickExec($fileMask,$fileMask,$command);
1039
1040 $blurTextImg_tmp = $this->imageCreateFromGif($fileMask); // the mask is loaded again
1041 if ($blurTextImg_tmp) { // if nothing went wrong we continue with the blurred mask
1042
1043 // cropping the border from the mask
1044 $blurTextImg = imagecreate($w,$h);
1045 $this->imagecopyresized($blurTextImg, $blurTextImg_tmp, 0, 0, $blurBorder, $blurBorder, $w, $h, $w, $h);
1046 ImageDestroy($blurTextImg_tmp); // Destroy the temporary mask
1047
1048 // adjust the mask
1049 $intensity = 40;
1050 if ($conf['intensity']) {
1051 $intensity = t3lib_div::intInRange($conf['intensity'],0,100);
1052 }
1053 $intensity = ceil(255-($intensity/100*255));
1054 $this->inputLevels($blurTextImg,0,$intensity,$this->maskNegate);
1055
1056 $opacity = t3lib_div::intInRange(intval($conf['opacity']),0,100);
1057 if ($opacity && $opacity<100) {
1058 $high = ceil(255*$opacity/100);
1059 $this->outputLevels($blurTextImg,0,$high,$this->maskNegate); // reducing levels as the opacity demands
1060 }
1061
1062 $this->ImageGif($blurTextImg, $fileMask); // Dump the mask again
1063 ImageDestroy($blurTextImg); // Destroy the mask
1064
1065 // The pictures are combined
1066 $this->ImageGif($im, $fileMenu); // The main pictures is saved temporarily
1067
1068 $this->combineExec($fileMenu,$fileColor,$fileMask,$fileMenu);
1069
1070 $backIm = $this->imageCreateFromGif($fileMenu); // The main image is loaded again...
1071 if ($backIm) { // ... and if nothing went wrong we load it onto the old one.
1072 ImageColorTransparent($backIm,-1);
1073 $im = $backIm;
1074 }
1075 }
1076 // Deleting temporary files;
1077 if (!$this->dontUnlinkTempFiles) {
1078 unlink($fileMenu);
1079 unlink($fileColor);
1080 unlink($fileMask);
1081 }
1082 }
1083 }
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105 /****************************
1106 *
1107 * Other GIFBUILDER objects
1108 *
1109 ****************************/
1110
1111 /**
1112 * Implements the "BOX" GIFBUILDER object
1113 *
1114 * @param pointer GDlib image pointer
1115 * @param array TypoScript array with configuration for the GIFBUILDER object.
1116 * @param array The current working area coordinates.
1117 * @return void
1118 * @see tslib_gifBuilder::make()
1119 */
1120 function makeBox(&$im,$conf,$workArea) {
1121 $cords = t3lib_div::intExplode(',',$conf['dimensions'].',,,');
1122 $conf['offset']=$cords[0].','.$cords[1];
1123 $cords = $this->objPosition($conf,$workArea,Array($cords[2],$cords[3]));
1124 $cols=$this->convertColor($conf['color']);
1125 $this->reduceColors($im,256, 255);
1126 $tmpColor = ImageColorAllocate($im, $cols[0],$cols[1],$cols[2]);
1127 imagefilledrectangle($im, $cords[0], $cords[1], $cords[0]+$cords[2]-1, $cords[1]+$cords[3]-1, $tmpColor);
1128 }
1129
1130 /**
1131 * Implements the "EFFECT" GIFBUILDER object
1132 * The operation involves ImageMagick for applying effects
1133 *
1134 * @param pointer GDlib image pointer
1135 * @param array TypoScript array with configuration for the GIFBUILDER object.
1136 * @return void
1137 * @see tslib_gifBuilder::make(), applyImageMagickToPHPGif()
1138 */
1139 function makeEffect(&$im, $conf) {
1140 $commands = $this->IMparams($conf['value']);
1141 if ($commands) {
1142 $this->applyImageMagickToPHPGif($im, $commands);
1143 }
1144 }
1145
1146 /**
1147 * Creating ImageMagick paramters from TypoScript property
1148 *
1149 * @param string A string with effect keywords=value pairs separated by "|"
1150 * @return string ImageMagick prepared parameters.
1151 * @access private
1152 * @see makeEffect()
1153 */
1154 function IMparams($setup) {
1155 if (!trim($setup)){return '';}
1156 $effects = explode('|', $setup);
1157 $commands = '';
1158 while(list(,$val)=each($effects)) {
1159 $pairs=explode('=',$val,2);
1160 $value = trim($pairs[1]);
1161 $effect = strtolower(trim($pairs[0]));
1162 switch($effect) {
1163 case 'gamma':
1164 $commands.=' -gamma '.doubleval($value);
1165 break;
1166 case 'blur':
1167 if (!$this->NO_IM_EFFECTS) {
1168 if ($this->V5_EFFECTS) {
1169 $commands.=$this->v5_blur($value);
1170 } else {
1171 $commands.=' -blur '.t3lib_div::intInRange($value,1,99);
1172 }
1173 }
1174 break;
1175 case 'sharpen':
1176 if (!$this->NO_IM_EFFECTS) {
1177 if ($this->V5_EFFECTS) {
1178 $commands.=$this->v5_sharpen($value);
1179 } else {
1180 $commands.=' -sharpen '.t3lib_div::intInRange($value,1,99);
1181 }
1182 }
1183 break;
1184 case 'rotate':
1185 $commands.=' -rotate '.t3lib_div::intInRange($value,0,360);
1186 break;
1187 case 'solarize':
1188 $commands.=' -solarize '.t3lib_div::intInRange($value,0,99);
1189 break;
1190 case 'swirl':
1191 $commands.=' -swirl '.t3lib_div::intInRange($value,0,1000);
1192 break;
1193 case 'wave':
1194 $params = t3lib_div::intExplode(',',$value);
1195 $commands.=' -wave '.t3lib_div::intInRange($params[0],0,99).'x'.t3lib_div::intInRange($params[1],0,99);
1196 break;
1197 case 'charcoal':
1198 $commands.=' -charcoal '.t3lib_div::intInRange($value,0,100);
1199 break;
1200 case 'gray':
1201 $commands.=' -colorspace GRAY';
1202 break;
1203 case 'edge':
1204 $commands.=' -edge '.t3lib_div::intInRange($value,0,99);
1205 break;
1206 case 'emboss':
1207 $commands.=' -emboss';
1208 break;
1209 case 'flip':
1210 $commands.=' -flip';
1211 break;
1212 case 'flop':
1213 $commands.=' -flop';
1214 break;
1215 case 'colors':
1216 $commands.=' -colors '.t3lib_div::intInRange($value,2,255);
1217 break;
1218 case 'shear':
1219 $commands.=' -shear '.t3lib_div::intInRange($value,-90,90);
1220 break;
1221 case 'invert':
1222 $commands.=' -negate';
1223 break;
1224 }
1225 }
1226 return $commands;
1227 }
1228
1229 /**
1230 * Implements the "ADJUST" GIFBUILDER object
1231 *
1232 * @param pointer GDlib image pointer
1233 * @param array TypoScript array with configuration for the GIFBUILDER object.
1234 * @return void
1235 * @see tslib_gifBuilder::make(), autoLevels(), outputLevels(), inputLevels()
1236 */
1237 function adjust(&$im, $conf) {
1238 $setup = $conf['value'];
1239 if (!trim($setup)){return '';}
1240 $effects = explode('|', $setup);
1241 while(list(,$val)=each($effects)) {
1242 $pairs=explode('=',$val,2);
1243 $value = trim($pairs[1]);
1244 $effect = strtolower(trim($pairs[0]));
1245 switch($effect) {
1246 case 'inputlevels': // low,high
1247 $params = t3lib_div::intExplode(',',$value);
1248 $this->inputLevels($im,$params[0],$params[1]);
1249 break;
1250 case 'outputlevels':
1251 $params = t3lib_div::intExplode(',',$value);
1252 $this->outputLevels($im,$params[0],$params[1]);
1253 break;
1254 case 'autolevels':
1255 $this->autoLevels($im);
1256 break;
1257 }
1258 }
1259 }
1260
1261 /**
1262 * Implements the "CROP" GIFBUILDER object
1263 *
1264 * @param pointer GDlib image pointer
1265 * @param array TypoScript array with configuration for the GIFBUILDER object.
1266 * @return void
1267 * @see tslib_gifBuilder::make()
1268 */
1269 function crop(&$im,$conf) {
1270 $this->setWorkArea(''); // clears workArea to total image
1271 $cords = t3lib_div::intExplode(',',$conf['crop'].',,,');
1272 $conf['offset']=$cords[0].','.$cords[1];
1273 $cords = $this->objPosition($conf,$this->workArea,Array($cords[2],$cords[3]));
1274
1275 $newIm = imagecreate($cords[2],$cords[3]);
1276 $cols=$this->convertColor($conf['backColor']?$conf['backColor']:$this->setup['backColor']);
1277 ImageColorAllocate($newIm, $cols[0],$cols[1],$cols[2]);
1278
1279 $newConf = Array();
1280 $workArea = Array(0,0,$cords[2],$cords[3]);
1281 if ($cords[0]<0) {$workArea[0]=abs($cords[0]);} else {$newConf['offset']=-$cords[0];}
1282 if ($cords[1]<0) {$workArea[1]=abs($cords[1]);} else {$newConf['offset'].=','.-$cords[1];}
1283
1284 $this->copyGifOntoGif($newIm,$im,$newConf,$workArea);
1285 $im = $newIm;
1286 $this->w = imagesx($im);
1287 $this->h = imagesy($im);
1288 $this->setWorkArea(''); // clears workArea to total image
1289 }
1290
1291 /**
1292 * Implements the "SCALE" GIFBUILDER object
1293 *
1294 * @param pointer GDlib image pointer
1295 * @param array TypoScript array with configuration for the GIFBUILDER object.
1296 * @return void
1297 * @see tslib_gifBuilder::make()
1298 */
1299 function scale(&$im,$conf) {
1300 if ($conf['width'] || $conf['height'] || $conf['params']) {
1301 $tmpStr = $this->randomName();
1302 $theFile = $tmpStr.'.'.$this->gifExtension;
1303 $this->ImageGif($im, $theFile);
1304 $theNewFile = $this->imageMagickConvert($theFile,$this->gifExtension,$conf['width'],$conf['height'],$conf['params'],'','');
1305 $tmpImg = $this->imageCreateFromGif($theNewFile[3]);
1306 if ($tmpImg) {
1307 ImageDestroy($im);
1308 $im = $tmpImg;
1309 $this->w = imagesx($im);
1310 $this->h = imagesy($im);
1311 $this->setWorkArea(''); // clears workArea to total image
1312 }
1313 if (!$this->dontUnlinkTempFiles) {
1314 unlink($theFile);
1315 if ($theNewFile[3] && $theNewFile[3]!=$theFile) {
1316 unlink($theNewFile[3]);
1317 }
1318 }
1319 }
1320 }
1321
1322 /**
1323 * Implements the "WORKAREA" GIFBUILDER object when setting it
1324 * Setting internal working area boundaries (->workArea)
1325 *
1326 * @param string Working area dimensions, comma separated
1327 * @return void
1328 * @access private
1329 * @see tslib_gifBuilder::make()
1330 */
1331 function setWorkArea($workArea) {
1332 $this->workArea = t3lib_div::intExplode(',',$workArea);
1333 $this->workArea = $this->applyOffset($this->workArea,$this->OFFSET);
1334 if (!$this->workArea[2]) {$this->workArea[2]=$this->w;}
1335 if (!$this->workArea[3]) {$this->workArea[3]=$this->h;}
1336 }
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360 /*************************
1361 *
1362 * Adjustment functions
1363 *
1364 ************************/
1365
1366 /**
1367 * Apply auto-levels to input image pointer
1368 *
1369 * @param integer GDlib Image Pointer
1370 * @return void
1371 */
1372 function autolevels(&$im) {
1373 $totalCols = ImageColorsTotal($im);
1374 $min=255;
1375 $max=0;
1376 for ($c=0; $c<$totalCols; $c++) {
1377 $cols = ImageColorsForIndex($im,$c);
1378 $grayArr[] = round(($cols['red']+$cols['green']+$cols['blue'])/3);
1379 }
1380 $min=min($grayArr);
1381 $max=max($grayArr);
1382 $delta = $max-$min;
1383 if ($delta) {
1384 for ($c=0; $c<$totalCols; $c++) {
1385 $cols = ImageColorsForIndex($im,$c);
1386 $cols['red'] = floor(($cols['red']-$min)/$delta*255);
1387 $cols['green'] = floor(($cols['green']-$min)/$delta*255);
1388 $cols['blue'] = floor(($cols['blue']-$min)/$delta*255);
1389 ImageColorSet($im,$c,$cols['red'],$cols['green'],$cols['blue']);
1390 }
1391 }
1392 }
1393
1394 /**
1395 * Apply output levels to input image pointer (decreasing contrast)
1396 *
1397 * @param integer GDlib Image Pointer
1398 * @param integer The "low" value (close to 0)
1399 * @param integer The "high" value (close to 255)
1400 * @param boolean If swap, then low and high are swapped. (Useful for negated masks...)
1401 * @return void
1402 */
1403 function outputLevels(&$im,$low,$high,$swap='') {
1404 if ($low<$high){
1405 $low = t3lib_div::intInRange($low,0,255);
1406 $high = t3lib_div::intInRange($high,0,255);
1407
1408 if ($swap) {
1409 $temp = $low;
1410 $low = 255-$high;
1411 $high = 255-$temp;
1412 }
1413
1414 $delta = $high-$low;
1415 $totalCols = ImageColorsTotal($im);
1416 for ($c=0; $c<$totalCols; $c++) {
1417 $cols = ImageColorsForIndex($im,$c);
1418 $cols['red'] = $low+floor($cols['red']/255*$delta);
1419 $cols['green'] = $low+floor($cols['green']/255*$delta);
1420 $cols['blue'] = $low+floor($cols['blue']/255*$delta);
1421 ImageColorSet($im,$c,$cols['red'],$cols['green'],$cols['blue']);
1422 }
1423 }
1424 }
1425
1426 /**
1427 * Apply input levels to input image pointer (increasing contrast)
1428 *
1429 * @param integer GDlib Image Pointer
1430 * @param integer The "low" value (close to 0)
1431 * @param integer The "high" value (close to 255)
1432 * @param boolean If swap, then low and high are swapped. (Useful for negated masks...)
1433 * @return void
1434 */
1435 function inputLevels(&$im,$low,$high,$swap='') {
1436 if ($low<$high){
1437 $low = t3lib_div::intInRange($low,0,255);
1438 $high = t3lib_div::intInRange($high,0,255);
1439
1440 if ($swap) {
1441 $temp = $low;
1442 $low = 255-$high;
1443 $high = 255-$temp;
1444 }
1445
1446 $delta = $high-$low;
1447 $totalCols = ImageColorsTotal($im);
1448 for ($c=0; $c<$totalCols; $c++) {
1449 $cols = ImageColorsForIndex($im,$c);
1450 $cols['red'] = t3lib_div::intInRange(($cols['red']-$low)/$delta*255, 0,255);
1451 $cols['green'] = t3lib_div::intInRange(($cols['green']-$low)/$delta*255, 0,255);
1452 $cols['blue'] = t3lib_div::intInRange(($cols['blue']-$low)/$delta*255, 0,255);
1453 ImageColorSet($im,$c,$cols['red'],$cols['green'],$cols['blue']);
1454 }
1455 }
1456 }
1457
1458 /**
1459 * Reduce colors in image
1460 *
1461 * @param integer GDlib Image Pointer
1462 * @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.
1463 * @param integer Number of colors to reduce the image to.
1464 * @return void
1465 */
1466 function reduceColors(&$im,$limit, $cols) {
1467 if (ImageColorsTotal($im)>=$limit) {
1468 $this->makeEffect($im, Array('value'=>'colors='.$cols) );
1469 }
1470 }
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490 /*********************************
1491 *
1492 * GIFBUILDER Helper functions
1493 *
1494 *********************************/
1495
1496 /**
1497 * Checks if the $fontFile is already at an absolute path and if not, prepends the correct path.
1498 * Use PATH_site unless we are in the backend.
1499 * Call it by t3lib_stdGraphic::prependAbsolutePath()
1500 *
1501 * @param string The font file
1502 * @return string The font file with absolute path.
1503 */
1504 function prependAbsolutePath($fontFile) {
1505 $absPath = defined('PATH_typo3') ? dirname(PATH_thisScript).'/' :PATH_site;
1506 $fontFile = t3lib_div::isAbsPath($fontFile) ? $fontFile : $absPath.$fontFile;
1507 return $fontFile;
1508 }
1509
1510 /**
1511 * Returns the IM command for sharpening with ImageMagick 5 (when $this->V5_EFFECTS is set).
1512 * Uses $this->im5fx_sharpenSteps for translation of the factor to an actual command.
1513 *
1514 * @param integer The sharpening factor, 0-100 (effectively in 10 steps)
1515 * @return string The sharpening command, eg. " -sharpen 3x4"
1516 * @see makeText(), IMparams(), v5_blur()
1517 */
1518 function v5_sharpen($factor) {
1519 $factor = t3lib_div::intInRange(ceil($factor/10),0,10);
1520
1521 $sharpenArr=explode(',',','.$this->im5fx_sharpenSteps);
1522 $sharpenF= trim($sharpenArr[$factor]);
1523 if ($sharpenF) {
1524 $cmd = ' -sharpen '.$sharpenF;
1525 return $cmd;
1526 }
1527 }
1528
1529 /**
1530 * Returns the IM command for blurring with ImageMagick 5 (when $this->V5_EFFECTS is set).
1531 * Uses $this->im5fx_blurSteps for translation of the factor to an actual command.
1532 *
1533 * @param integer The blurring factor, 0-100 (effectively in 10 steps)
1534 * @return string The blurring command, eg. " -blur 3x4"
1535 * @see makeText(), IMparams(), v5_sharpen()
1536 */
1537 function v5_blur($factor) {
1538 $factor = t3lib_div::intInRange(ceil($factor/10),0,10);
1539
1540 $blurArr=explode(',',','.$this->im5fx_blurSteps);
1541 $blurF= trim($blurArr[$factor]);
1542 if ($blurF) {
1543 $cmd=' -blur '.$blurF;
1544 return $cmd;
1545 }
1546 }
1547
1548 /**
1549 * Returns a random filename prefixed with "temp_" and then 32 char md5 hash (without extension) from $this->tempPath.
1550 * 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.
1551 *
1552 * @return string
1553 */
1554 function randomName() {
1555 return $this->tempPath.'temp_'.md5(uniqid(''));
1556 }
1557
1558 /**
1559 * Applies offset value to coordinated in $cords.
1560 * Basically the value of key 0/1 of $OFFSET is added to keys 0/1 of $cords
1561 *
1562 * @param array Integer coordinates in key 0/1
1563 * @param array Offset values in key 0/1
1564 * @return array Modified $cords array
1565 */
1566 function applyOffset($cords,$OFFSET) {
1567 $cords[0] = intval($cords[0])+intval($OFFSET[0]);
1568 $cords[1] = intval($cords[1])+intval($OFFSET[1]);
1569 return $cords;
1570 }
1571
1572 /**
1573 * Converts a "HTML-color" TypoScript datatype to RGB-values.
1574 * Default is 0,0,0
1575 *
1576 * @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
1577 * @return array RGB values in key 0/1/2 of the array
1578 */
1579 function convertColor($string) {
1580 $col=array();
1581 $cParts = explode(':',$string,2);
1582
1583 // Finding the RGB definitions of the color:
1584 $string=$cParts[0];
1585 if (strstr($string,'#')) {
1586 $string = ereg_replace('[^A-Fa-f0-9]*','',$string);
1587 $col[]=HexDec(substr($string,0,2));
1588 $col[]=HexDec(substr($string,2,2));
1589 $col[]=HexDec(substr($string,4,2));
1590 } elseif (strstr($string,',')) {
1591 $string = ereg_replace('[^,0-9]*','',$string);
1592 $strArr = explode(',',$string);
1593 $col[]=intval($strArr[0]);
1594 $col[]=intval($strArr[1]);
1595 $col[]=intval($strArr[2]);
1596 } else {
1597 $string = strtolower(trim($string));
1598 if ($this->colMap[$string]) {
1599 $col = $this->colMap[$string];
1600 } else {
1601 $col = Array(0,0,0);
1602 }
1603 }
1604 // ... and possibly recalculating the value
1605 if (trim($cParts[1])) {
1606 $cParts[1]=trim($cParts[1]);
1607 if (substr($cParts[1],0,1)=='*') {
1608 $val=doubleval(substr($cParts[1],1));
1609 $col[0]=t3lib_div::intInRange($col[0]*$val,0,255);
1610 $col[1]=t3lib_div::intInRange($col[1]*$val,0,255);
1611 $col[2]=t3lib_div::intInRange($col[2]*$val,0,255);
1612 } else {
1613 $val=intval($cParts[1]);
1614 $col[0]=t3lib_div::intInRange($col[0]+$val,0,255);
1615 $col[1]=t3lib_div::intInRange($col[1]+$val,0,255);
1616 $col[2]=t3lib_div::intInRange($col[2]+$val,0,255);
1617 }
1618 }
1619 return $col;
1620 }
1621
1622 /**
1623 * Recode string
1624 * Used with text strings for fonts when languages has other character sets.
1625 *
1626 * @param string The text to recode
1627 * @return string The recoded string. Should be UTF-8 output. MAY contain entities (eg. &#123; or &#quot; which should render as real chars).
1628 */
1629 function recodeString($string) {
1630 // Recode string to UTF-8 from $this->nativeCharset:
1631 if ($this->nativeCharset && $this->nativeCharset!='utf-8') {
1632 $string = $this->csConvObj->utf8_encode($string,$this->nativeCharset); // Convert to UTF-8
1633 }
1634
1635 // Recode string accoding to TTFLocaleConv. Depreciated.
1636 if ($this->TTFLocaleConv) {
1637 $string = recode_string($this->TTFLocaleConv,$string);
1638 }
1639
1640 return $string;
1641 }
1642
1643 /**
1644 * Split a string into an array of individual characters
1645 * 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.
1646 *
1647 * @param string The text string to spli
1648 * @return array Numerical array with a char as each value.
1649 */
1650 function singleChars($theText) {
1651 if ($this->nativeCharset) {
1652 return $this->csConvObj->utf8_to_numberarray($theText,1,1); // Get an array of separated UTF-8 chars
1653 } else {
1654 $output=array();
1655 $c=strlen($theText);
1656 for($a=0;$a<$c;$a++) {
1657 $output[]=substr($theText,$a,1);
1658 }
1659 return $output;
1660 }
1661 }
1662
1663 /**
1664 * 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
1665 *
1666 * @param array TypoScript configuration for a GIFBUILDER object
1667 * @param array Workarea definition
1668 * @param array BB (Bounding box) array. Not just used for TEXT objects but also for others
1669 * @return array [0]=x, [1]=y, [2]=w, [3]=h
1670 * @access private
1671 * @see copyGifOntoGif(), makeBox(), crop()
1672 */
1673 function objPosition($conf,$workArea,$BB) {
1674 // offset, align, valign, workarea
1675 $result=Array();
1676 $result[2] = $BB[0];
1677 $result[3] = $BB[1];
1678 $w=$workArea[2];
1679 $h=$workArea[3];
1680
1681 $align = explode(',',$conf['align']);
1682 $align[0] = strtolower(substr(trim($align[0]),0,1));
1683 $align[1] = strtolower(substr(trim($align[1]),0,1));
1684
1685 switch($align[0]) {
1686 case 'r':
1687 $result[0]=$w-$result[2];
1688 break;
1689 case 'c':
1690 $result[0] = round(($w-$result[2])/2);
1691 break;
1692 default:
1693 $result[0] = 0;
1694 break;
1695 }
1696 switch($align[1]) {
1697 case 'b':
1698 $result[1] = $h-$result[3]; // y pos
1699 break;
1700 case 'c':
1701 $result[1] = round(($h-$result[3])/2);
1702 break;
1703 default:
1704 $result[1]=0;
1705 break;
1706 }
1707 $result = $this->applyOffset($result,t3lib_div::intExplode(',',$conf['offset']));
1708 $result = $this->applyOffset($result,$workArea);
1709 return $result;
1710 }
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732 /***********************************
1733 *
1734 * Scaling, Dimensions of images
1735 *
1736 ***********************************/
1737
1738 /**
1739 * Converts $imagefile to another file in temp-dir of type $newExt (extension).
1740 *
1741 * @param string The image filepath
1742 * @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.
1743 * @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
1744 * @param string Height. See $w
1745 * @param string Additional ImageMagick parameters.
1746 * @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...
1747 * @param array An array with options passed to getImageScale (see this function).
1748 * @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.
1749 * @return array [0]/[1] is w/h, [2] is file extension and [3] is the filename.
1750 * @see getImageScale(), typo3/show_item.php, fileList_ext::renderImage(), tslib_cObj::getImgResource(), SC_tslib_showpic::show(), maskImageOntoImage(), copyImageOntoImage(), scale()
1751 */
1752 function imageMagickConvert($imagefile,$newExt='',$w='',$h='',$params='',$frame='',$options='',$mustCreate=0) {
1753 if ($this->NO_IMAGE_MAGICK) {
1754 // Returning file info right away
1755 return $this->getImageDimensions($imagefile);
1756 }
1757
1758 if($info=$this->getImageDimensions($imagefile)) {
1759 $newExt=strtolower(trim($newExt));
1760 if (!$newExt) { // If no extension is given the original extension is used
1761 $newExt = $info[2];
1762 }
1763 if ($newExt=='web') {
1764 if (t3lib_div::inList($this->webImageExt,$info[2])) {
1765 $newExt = $info[2];
1766 } else {
1767 $newExt = $this->gif_or_jpg($info[2],$info[0],$info[1]);
1768 if (!$params) {
1769 $params = $this->cmds[$newExt];
1770 }
1771 }
1772 }
1773 if (t3lib_div::inList($this->imageFileExt,$newExt)) {
1774 if (strstr($w.$h, 'm')) {$max=1;} else {$max=0;}
1775
1776 $data = $this->getImageScale($info,$w,$h,$options);
1777 $w=$data['origW'];
1778 $h=$data['origH'];
1779
1780 // if no convertion should be performed
1781 $wh_noscale = (!$w && !$h) || ($data[0]==$info[0] && $data[1]==$info[1]); // this flag is true if the width / height does NOT dictate the image to be scaled!! (that is if no w/h is given or if the destination w/h matches the original image-dimensions....
1782
1783 if ($wh_noscale && !$params && !$frame && $newExt==$info[2] && !$mustCreate) {
1784 $info[3] = $imagefile;
1785 return $info;
1786 }
1787 $info[0]=$data[0];
1788 $info[1]=$data[1];
1789
1790 $frame = $this->noFramePrepended ? '' : '['.intval($frame).']';
1791
1792 if (!$params) {
1793 $params = $this->cmds[$newExt];
1794 }
1795
1796 $command = $this->scalecmd.' '.$info[0].'x'.$info[1].'! '.$params.' ';
1797
1798 if ($this->alternativeOutputKey) {
1799 $theOutputName = t3lib_div::shortMD5($command.basename($imagefile).$this->alternativeOutputKey.$frame);
1800 } else {
1801 $theOutputName = t3lib_div::shortMD5($command.$imagefile.filemtime($imagefile).$frame);
1802 }
1803 if ($this->imageMagickConvert_forceFileNameBody) {
1804 $theOutputName = $this->imageMagickConvert_forceFileNameBody;
1805 $this->imageMagickConvert_forceFileNameBody='';
1806 }
1807 $output = $this->tempPath.$this->filenamePrefix.$theOutputName.'.'.$newExt;
1808 $GLOBALS['TEMP_IMAGES_ON_PAGE'][]=$output;
1809
1810 if (!$this->file_exists_typo3temp_file($output,$imagefile) || $this->dontCheckForExistingTempFile) {
1811 $this->imageMagickExec($imagefile.$frame,$output,$command);
1812 }
1813 if (@file_exists($output)) {
1814 $info[3] = $output;
1815 $info[2] = $newExt;
1816 if ($params) { // params could realisticly change som imagedata!
1817 $info=$this->getImageDimensions($info[3]);
1818 }
1819 if ($info[2]==$this->gifExtension && !$this->dontCompress) {
1820 t3lib_div::gif_compress($info[3],''); // Compress with IM (lzw) or GD (rle) (Workaround for the absence of lzw-compression in GD)
1821 }
1822 return $info;
1823 }
1824 }
1825 }
1826 }
1827
1828 /**
1829 * Gets the input image dimensions.
1830 *
1831 * @param string The image filepath
1832 * @return array Returns an array where [0]/[1] is w/h, [2] is extension and [3] is the filename.
1833 * @see imageMagickConvert(), tslib_cObj::getImgResource()
1834 */
1835 function getImageDimensions($imageFile) {
1836 ereg('([^\.]*)$',$imageFile,$reg);
1837 if (@file_exists($imageFile) && t3lib_div::inList($this->imageFileExt,strtolower($reg[0]))) {
1838 if ($returnArr = $this->getCachedImageDimensions($imageFile)) {
1839 return $returnArr;
1840 } else {
1841 if ($temp = @getImageSize($imageFile)) {
1842 $returnArr = Array($temp[0], $temp[1], strtolower($reg[0]), $imageFile);
1843 } else {
1844 $returnArr = $this->imageMagickIdentify($imageFile);
1845 }
1846 if($returnArr) {
1847 $this->cacheImageDimensions($returnArr);
1848 return $returnArr;
1849 }
1850 }
1851 }
1852 return false;
1853 }
1854
1855 /**
1856 * Cache the result of the getImageDimensions function into the database. Does not check if the
1857 * file exists!
1858 *
1859 * @param array $identifyResult: Result of the getImageDimensions function
1860 * @return boolean True if operation was successful
1861 * @author Michael Stucki <mundaun@gmx.ch> / Robert Lemke <rl@robertlemke.de>
1862 */
1863 function cacheImageDimensions($identifyResult) {
1864 global $TYPO3_DB;
1865 // Create a md5 hash of the filename
1866 if (function_exists('md5_file')) {
1867 $md5Hash = md5_file($identifyResult[3]);
1868 } else {
1869 $md5Hash = md5 (t3lib_div::getURL($identifyResult[3]));
1870 }
1871 if ($md5Hash) {
1872 $fieldArr = array (
1873 'md5hash' => $md5Hash,
1874 'md5filename' => md5($identifyResult[3]),
1875 'tstamp' => time(),
1876 'filename' => $identifyResult[3],
1877 'imagewidth' => $identifyResult[0],
1878 'imageheight' => $identifyResult[1],
1879 );
1880 $TYPO3_DB->exec_INSERTquery('cache_imagesizes', $fieldArr);
1881 if (!$err = $TYPO3_DB->sql_error()) {
1882 return true;
1883 }
1884 }
1885 return false;
1886 }
1887
1888 /**
1889 * Fetch the cached imageDimensions from the MySQL database. Does not check if the image file exists!
1890 *
1891 * @param string The image filepath
1892 * @return array Returns an array where [0]/[1] is w/h, [2] is extension and [3] is the filename.
1893 * @author Michael Stucki <mundaun@gmx.ch> / Robert Lemke <rl@robertlemke.de>
1894 */
1895 function getCachedImageDimensions($imageFile) {
1896 global $TYPO3_DB;
1897 // Create a md5 hash of the filename
1898 if(function_exists('md5_file')) {
1899 $md5Hash = md5_file($imageFile);
1900 } else {
1901 $md5Hash = md5(t3lib_div::getURL ($imageFile));
1902 }
1903 ereg('([^\.]*)$',$imageFile,$reg);
1904 $res = $TYPO3_DB->exec_SELECTquery ('md5hash, imagewidth, imageheight', 'cache_imagesizes', 'md5filename="'.md5($imageFile).'"');
1905 if ($res) {
1906 if ($row = $TYPO3_DB->sql_fetch_assoc($res)) {
1907 if ($row['md5hash']!=$md5Hash) {
1908 // file has changed, delete the row
1909 $TYPO3_DB->exec_DELETEquery ('cache_imagesizes', 'md5hash="'.$TYPO3_DB->quoteStr($row['md5hash']).'"');
1910 } else {
1911 return (array($row['imagewidth'], $row['imageheight'], strtolower($reg[0]), $imageFile));
1912 }
1913 }
1914 }
1915 return false;
1916 }
1917
1918 /**
1919 * Get numbers for scaling the image based on input
1920 *
1921 * @param array Current image information: Width, Height etc.
1922 * @param integer "required" width
1923 * @param integer "required" height
1924 * @param array Options: Keys are like "maxW", "maxH", "minW", "minH"
1925 * @return array
1926 * @access private
1927 * @see imageMagickConvert()
1928 */
1929 function getImageScale($info,$w,$h,$options) {
1930 if (strstr($w.$h, 'm')) {$max=1;} else {$max=0;}
1931 $w=intval($w);
1932 $h=intval($h);
1933 // if there are max-values...
1934 if ($options['maxW']) {
1935 if ($w) { // if width is given...
1936 if ($w>$options['maxW']) {
1937 $w=$options['maxW'];
1938 $max=1; // height should follow
1939 }
1940 } else {
1941 if ($info[0]>$options['maxW']) {
1942 $w=$options['maxW'];
1943 $max=1; // height should follow
1944 }
1945 }
1946 }
1947 if ($options['maxH']) {
1948 if ($h) { // if height is given...
1949 if ($h>$options['maxH']) {
1950 $h=$options['maxH'];
1951 $max=1; // height should follow
1952 }
1953 } else {
1954 if ($info[1]>$options['maxH']) { // Changed [0] to [1] 290801
1955 $h=$options['maxH'];
1956 $max=1; // height should follow
1957 }
1958 }
1959 }
1960 $out['origW']=$w;
1961 $out['origH']=$h;
1962 $out['max'] = $max;
1963
1964 if (!$this->mayScaleUp) {
1965 if ($w>$info[0]){$w=$info[0];}
1966 if ($h>$info[1]){$h=$info[1];}
1967 }
1968 if ($w || $h) { // if scaling should be performed
1969 if ($w && !$h) {
1970 $info[1] = ceil($info[1]*($w/$info[0]));
1971 $info[0] = $w;
1972 }
1973 if (!$w && $h) {
1974 $info[0] = ceil($info[0]*($h/$info[1]));
1975 $info[1] = $h;
1976 }
1977 if ($w && $h) {
1978 if ($max) {
1979 $ratio = $info[0]/$info[1];
1980 if ($h*$ratio > $w) {
1981 $h = round($w/$ratio);
1982 } else {
1983 $w = round($h*$ratio);
1984 }
1985 }
1986 $info[0] = $w;
1987 $info[1] = $h;
1988 }
1989 }
1990 $out[0]=$info[0];
1991 $out[1]=$info[1];
1992 // Set minimum-measures!
1993 if ($options['minW'] && $out[0]<$options['minW']) {
1994 if ($max && $out[0]) {
1995 $out[1]= round($out[1]*$options['minW']/$out[0]);
1996 }
1997 $out[0]=$options['minW'];
1998 }
1999 if ($options['minH'] && $out[1]<$options['minH']) {
2000 if ($max && $out[1]) {
2001 $out[0]= round($out[0]*$options['minH']/$out[1]);
2002 }
2003 $out[1]=$options['minH'];
2004 }
2005
2006 return $out;
2007 }
2008
2009 /**
2010 * Used to check if a certain process of scaling an image is already being carried out (can be logged in the SQL database)
2011 *
2012 * @param string Output imagefile
2013 * @param string Original basis file
2014 * @return boolean Returns true if the file is already being made; thus "true" means "Don't render the image again"
2015 * @access private
2016 */
2017 function file_exists_typo3temp_file($output,$orig='') {
2018 if ($this->enable_typo3temp_db_tracking) {
2019 if (@file_exists($output)) { // If file exists, then we return immediately
2020 return 1;
2021 } else { // If not, we look up in the cache_typo3temp_log table to see if there is a image being rendered right now.
2022 $md5Hash=md5($output);
2023 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('md5hash', 'cache_typo3temp_log', 'md5hash="'.$GLOBALS['TYPO3_DB']->quoteStr($md5Hash, 'cache_typo3temp_log').'" AND tstamp>'.(time()-30));
2024 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) { // If there was a record, the image is being generated by another proces (we assume)
2025 if (is_object($GLOBALS['TSFE'])) $GLOBALS['TSFE']->set_no_cache(); // ...so we set no_cache, because we dont want this page (which will NOT display an image...!) to be cached! (Only a page with the correct image on...)
2026 if (is_object($GLOBALS['TT'])) $GLOBALS['TT']->setTSlogMessage('typo3temp_log: Assume this file is being rendered now: '.$output);
2027 return 2; // Return 'success - 2'
2028 } 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.
2029
2030 $insertFields = array(
2031 'md5hash' => $md5Hash,
2032 'tstamp' => time(),
2033 'filename' => $output,
2034 'orig_filename' => $orig
2035 );
2036 $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_typo3temp_log', 'md5hash="'.$GLOBALS['TYPO3_DB']->quoteStr($md5Hash, 'cache_typo3temp_log').'"');
2037 $GLOBALS['TYPO3_DB']->exec_INSERTquery('cache_typo3temp_log', $insertFields);
2038
2039 if (is_object($GLOBALS['TT'])) $GLOBALS['TT']->setTSlogMessage('typo3temp_log: The row did not exist, so a new is written and file is being processed: '.$output);
2040 return 0;
2041 }
2042 }
2043 } else {
2044 return @file_exists($output);
2045 }
2046 }
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065 /***********************************
2066 *
2067 * ImageMagick API functions
2068 *
2069 ***********************************/
2070
2071 /**
2072 * Returns an array where [0]/[1] is w/h, [2] is extension and [3] is the filename.
2073 * Using ImageMagick
2074 *
2075 * @param string The absolute image filepath
2076 * @return array
2077 */
2078 function imageMagickIdentify($imagefile) {
2079 if (!$this->NO_IMAGE_MAGICK) {
2080 $cmd = $this->imageMagickPath.'identify '.$this->wrapFileName($imagefile);
2081 exec($cmd, $returnVal);
2082 $splitstring=$returnVal[0];
2083 $this->IM_commands[] = Array ('identify',$cmd,$returnVal[0]);
2084 if ($splitstring) {
2085 ereg('([^\.]*)$',$imagefile,$reg);
2086 $splitinfo = explode(' ', $splitstring);
2087 while (list($key,$val) = each($splitinfo)) {
2088 $temp = '';
2089 if ($val) {$temp = explode('x', $val);}
2090 if (intval($temp[0]) && intval($temp[1])) {
2091 $dim=$temp;
2092 break;
2093 }
2094 }
2095 if ($dim[0] && $dim[1]) {
2096 return Array($dim[0], $dim[1], strtolower($reg[0]), $imagefile);
2097 }
2098 }
2099 }
2100 }
2101
2102 /**
2103 * Executes a ImageMagick "convert" on two filenames, $input and $output using $params before them.
2104 * Can be used for many things, mostly scaling and effects.
2105 *
2106 * @param string The absolute image filepath, input file (read from)
2107 * @param string The absolute image filepath, output filename (written to)
2108 * @param string ImageMagick parameters
2109 * @return string The result of a call to PHP function "exec()"
2110 */
2111 function imageMagickExec($input,$output,$params) {
2112 if (!$this->NO_IMAGE_MAGICK) {
2113 $cmd = $this->imageMagickPath.'convert '.$params.' '.$this->wrapFileName($input).' '.$this->wrapFileName($output);
2114 $this->IM_commands[] = Array ($output,$cmd);
2115 return exec($cmd);
2116 }
2117 }
2118
2119 /**
2120 * 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)
2121 * Can be used for many things, mostly scaling and effects.
2122 *
2123 * @param string The absolute image filepath, bottom file
2124 * @param string The absolute image filepath, overlay file (top)
2125 * @param string The absolute image filepath, the mask file (grayscale)
2126 * @param string The absolute image filepath, output filename (written to)
2127 * @return void
2128 */
2129 function combineExec($input,$overlay,$mask,$output) {
2130 if (!$this->NO_IMAGE_MAGICK) {
2131 $cmd = $this->imageMagickPath.$this->combineScript.' -compose over '.$this->wrapFileName($input).' '.$this->wrapFileName($overlay).' '.$this->wrapFileName($mask).' '.$this->wrapFileName($output);
2132 $this->IM_commands[] = Array ($output,$cmd);
2133 exec($cmd);
2134 }
2135 }
2136
2137 /**
2138 * Wrapping the input filename in double-quotes
2139 *
2140 * @param string Input filename
2141 * @return string The output wrapped in "" (if there are spaces in the filepath)
2142 * @access private
2143 */
2144 function wrapFileName($inputName) {
2145 if (strstr($inputName,' ')) {
2146 $inputName='"'.$inputName.'"';
2147 }
2148 return $inputName;
2149 }
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173 /***********************************
2174 *
2175 * Various IO functions
2176 *
2177 ***********************************/
2178
2179 /**
2180 * Returns true if the input file existed
2181 *
2182 * @param string Input file to check
2183 * @return string Returns the filename if the file existed, otherwise empty.
2184 */
2185 function checkFile($file) {
2186 if (@is_file($file)) {
2187 return $file;
2188 } else {
2189 return '';
2190 }
2191 }
2192
2193 /**
2194 * 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.
2195 *
2196 * @param pointer The image pointer (reference)
2197 * @param string The ImageMagick parameters. Like effects, scaling etc.
2198 * @return void
2199 */
2200 function applyImageMagickToPHPGif(&$im, $command) {
2201 $tmpStr = $this->randomName();
2202 $theFile = $tmpStr.'.'.$this->gifExtension;
2203 $this->ImageGif($im, $theFile);
2204 $this->imageMagickExec($theFile,$theFile,$command);
2205 $tmpImg = $this->imageCreateFromGif($theFile);
2206 if ($tmpImg) {
2207 ImageDestroy($im);
2208 $im = $tmpImg;
2209 $this->w = imagesx($im);
2210 $this->h = imagesy($im);
2211 }
2212 if (!$this->dontUnlinkTempFiles) {
2213 unlink($theFile);
2214 }
2215 }
2216
2217 /**
2218 * 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.
2219 * For example: If the number of pixels exceeds $this->pixelLimitGif (normally 10000) then it will be a "jpg" string in return.
2220 *
2221 * @param string The file extension, lowercase.
2222 * @param integer The width of the output image.
2223 * @param integer The height of the output image.
2224 * @return string The filename, either "jpg" or "gif"/"png" (whatever $this->gifExtension is set to.)
2225 */
2226 function gif_or_jpg($type,$w,$h) {
2227 if ($type=='ai' || $w*$h < $this->pixelLimitGif) {
2228 return $this->gifExtension;
2229 } else {
2230 return 'jpg';
2231 }
2232 }
2233
2234 /**
2235 * Writing the internal image pointer, $this->im, to file based on the extension of the input filename
2236 * Used in GIFBUILDER
2237 * Uses $this->setup['reduceColors'] for gif/png images and $this->setup['quality'] for jpg images to reduce size/quality if needed.
2238 *
2239 * @param string The filename to write to.
2240 * @return string Returns input filename
2241 * @see tslib_gifBuilder::gifBuild()
2242 */
2243 function output($file) {
2244 if ($file) {
2245 ereg('([^\.]*)$',$file,$reg);
2246 $ext=strtolower($reg[0]);
2247 switch($ext) {
2248 case $this->gifExtension:
2249 if ($this->ImageGif($this->im, $file)) {
2250 // ImageMagick operations
2251 if($this->setup['reduceColors']) {
2252 $this->imageMagickExec($file,$file,' -colors '.t3lib_div::intInRange($this->setup['reduceColors'],2,255));
2253 t3lib_div::gif_compress($file,''); // Compress with IM (lzw) or GD (rle) (Workaround for the absence of lzw-compression in GD)
2254 } else {
2255 t3lib_div::gif_compress($file, 'IM'); // Compress with IM! (adds extra compression, LZW from ImageMagick) (Workaround for the absence of lzw-compression in GD)
2256 }
2257 }
2258 break;
2259 case 'jpg':
2260 case 'jpeg':
2261 $tmpStr = $this->randomName();
2262 $theFile = $tmpStr.'.'.$this->gifExtension;
2263 if ($this->ImageGif($this->im, $theFile)) {
2264 // ImageMagick operations
2265 $operations='';
2266 if($this->setup['quality']) {
2267 $operations.=' -quality '.t3lib_div::intInRange($this->setup['quality'],10,100);
2268 }
2269 $this->imageMagickExec($theFile,$file,$operations);
2270 if (!$this->dontUnlinkTempFiles) {
2271 unlink($theFile);
2272 }
2273 }
2274 break;
2275 }
2276 $GLOBALS['TEMP_IMAGES_ON_PAGE'][]=$file;
2277 }
2278 return $file;
2279 }
2280
2281 /**
2282 * Destroy internal image pointer, $this->im
2283 *
2284 * @return void
2285 * @see tslib_gifBuilder::gifBuild()
2286 */
2287 function destroy() {
2288 ImageDestroy($this->im);
2289 }
2290
2291 /**
2292 * Returns Image Tag for input image information array.
2293 *
2294 * @param array Image information array, key 0/1 is width/height and key 3 is the src value
2295 * @return string Image tag for the input image information array.
2296 */
2297 function imgTag ($imgInfo) {
2298 return '<img src="'.$imgInfo[3].'" width="'.$imgInfo[0].'" height="'.$imgInfo[1].'" border="0" alt="" />';
2299 }
2300
2301 /**
2302 * Writes the input GDlib image pointer to file
2303 *
2304 * @param pointer The GDlib image resource pointer
2305 * @param string The filename to write to
2306 * @return mixed The output of either imageGif or imagePng based on whether the $this->gifExtension was set to "gif" or "png"
2307 * @see maskImageOntoImage(), scale(), output()
2308 */
2309 function ImageGif($destImg, $theImage) {
2310 imageinterlace ($destImg,0);
2311 if ($this->gifExtension=='gif') {
2312 return ImageGif($destImg, $theImage);
2313 }
2314 if ($this->gifExtension=='png') {
2315 return ImagePng($destImg, $theImage);
2316 }
2317 }
2318
2319 /**
2320 * Creates a new GDlib image resource based on the input image filename.
2321 * If it fails creating a image from the input file a blank gray image with the dimensions of the input image will be created instead.
2322 *
2323 * @param string Image filename
2324 * @return pointer Image Resource pointer
2325 */
2326 function imageCreateFromGif($sourceImg) {
2327 $imgInf = pathinfo($sourceImg);
2328 $ext = strtolower($imgInf['extension']);
2329
2330 // if ($ext=='gif' && (ImageTypes() & IMG_GIF)) {
2331 if ($ext=='gif' && function_exists('imagecreatefromgif')) {
2332 return imageCreateFromGif($sourceImg);
2333 }
2334 // if ($ext=='png' && (ImageTypes() & IMG_PNG)) {
2335 if ($ext=='png' && function_exists('imagecreatefrompng')) {
2336 return imageCreateFromPng($sourceImg);
2337 }
2338 // if (($ext=='jpg' || $ext=='jpeg') && (ImageTypes() & IMG_JPG)) {
2339 if (($ext=='jpg' || $ext=='jpeg') && function_exists('imagecreatefromjpeg')) {
2340 return imageCreateFromJpeg($sourceImg);
2341 }
2342
2343 // If non of the above:
2344 $i = @getimagesize($sourceImg);
2345 $im = imagecreate($i[0],$i[1]);
2346 ImageColorAllocate($im, 128,128,128);
2347 return $im;
2348 }
2349 }
2350
2351
2352 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_stdgraphic.php']) {
2353 include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_stdgraphic.php']);
2354 }
2355 ?>