3 * Generic handler for bitmap images
10 * Generic handler for bitmap images
14 class BitmapHandler
extends ImageHandler
{
17 * @param $params array Transform parameters. Entries with the keys 'width'
18 * and 'height' are the respective screen width and height, while the keys
19 * 'physicalWidth' and 'physicalHeight' indicate the thumbnail dimensions.
22 function normaliseParams( $image, &$params ) {
23 if ( !parent
::normaliseParams( $image, $params ) ) {
27 # Obtain the source, pre-rotation dimensions
28 $srcWidth = $image->getWidth( $params['page'] );
29 $srcHeight = $image->getHeight( $params['page'] );
31 # Don't make an image bigger than the source
32 if ( $params['physicalWidth'] >= $srcWidth ) {
33 $params['physicalWidth'] = $srcWidth;
34 $params['physicalHeight'] = $srcHeight;
36 # Skip scaling limit checks if no scaling is required
37 # due to requested size being bigger than source.
38 if ( !$image->mustRender() ) {
43 # Check if the file is smaller than the maximum image area for thumbnailing
44 $checkImageAreaHookResult = null;
45 wfRunHooks( 'BitmapHandlerCheckImageArea', array( $image, &$params, &$checkImageAreaHookResult ) );
46 if ( is_null( $checkImageAreaHookResult ) ) {
47 global $wgMaxImageArea;
49 if ( $srcWidth * $srcHeight > $wgMaxImageArea &&
50 !( $image->getMimeType() == 'image/jpeg' &&
51 self
::getScalerType( false, false ) == 'im' ) ) {
52 # Only ImageMagick can efficiently downsize jpg images without loading
53 # the entire file in memory
57 return $checkImageAreaHookResult;
65 * Extracts the width/height if the image will be scaled before rotating
67 * This will match the physical size/aspect ratio of the original image
68 * prior to application of the rotation -- so for a portrait image that's
69 * stored as raw landscape with 90-degress rotation, the resulting size
70 * will be wider than it is tall.
72 * @param $params array Parameters as returned by normaliseParams
73 * @param $rotation int The rotation angle that will be applied
74 * @return array ($width, $height) array
76 public function extractPreRotationDimensions( $params, $rotation ) {
77 if ( $rotation == 90 ||
$rotation == 270 ) {
78 # We'll resize before rotation, so swap the dimensions again
79 $width = $params['physicalHeight'];
80 $height = $params['physicalWidth'];
82 $width = $params['physicalWidth'];
83 $height = $params['physicalHeight'];
85 return array( $width, $height );
90 * Function that returns the number of pixels to be thumbnailed.
91 * Intended for animated GIFs to multiply by the number of frames.
96 function getImageArea( $image ) {
97 return $image->getWidth() * $image->getHeight();
106 * @return MediaTransformError|ThumbnailImage|TransformParameterError
108 function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
109 if ( !$this->normaliseParams( $image, $params ) ) {
110 return new TransformParameterError( $params );
112 # Create a parameter array to pass to the scaler
113 $scalerParams = array(
114 # The size to which the image will be resized
115 'physicalWidth' => $params['physicalWidth'],
116 'physicalHeight' => $params['physicalHeight'],
117 'physicalDimensions' => "{$params['physicalWidth']}x{$params['physicalHeight']}",
118 # The size of the image on the page
119 'clientWidth' => $params['width'],
120 'clientHeight' => $params['height'],
121 # Comment as will be added to the EXIF of the thumbnail
122 'comment' => isset( $params['descriptionUrl'] ) ?
123 "File source: {$params['descriptionUrl']}" : '',
124 # Properties of the original image
125 'srcWidth' => $image->getWidth(),
126 'srcHeight' => $image->getHeight(),
127 'mimeType' => $image->getMimeType(),
128 'dstPath' => $dstPath,
132 # Determine scaler type
133 $scaler = self
::getScalerType( $dstPath );
135 wfDebug( __METHOD__
. ": creating {$scalerParams['physicalDimensions']} thumbnail at $dstPath using scaler $scaler\n" );
137 if ( !$image->mustRender() &&
138 $scalerParams['physicalWidth'] == $scalerParams['srcWidth']
139 && $scalerParams['physicalHeight'] == $scalerParams['srcHeight'] ) {
141 # normaliseParams (or the user) wants us to return the unscaled image
142 wfDebug( __METHOD__
. ": returning unscaled image\n" );
143 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
147 if ( $scaler == 'client' ) {
148 # Client-side image scaling, use the source URL
149 # Using the destination URL in a TRANSFORM_LATER request would be incorrect
150 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
153 if ( $flags & self
::TRANSFORM_LATER
) {
154 wfDebug( __METHOD__
. ": Transforming later per flags.\n" );
155 return new ThumbnailImage( $image, $dstUrl, $scalerParams['clientWidth'],
156 $scalerParams['clientHeight'], false );
159 # Try to make a target path for the thumbnail
160 if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__
) ) {
161 wfDebug( __METHOD__
. ": Unable to create thumbnail destination directory, falling back to client scaling\n" );
162 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
165 # Transform functions and binaries need a FS source file
166 $scalerParams['srcPath'] = $image->getLocalRefPath();
170 wfRunHooks( 'BitmapHandlerTransform', array( $this, $image, &$scalerParams, &$mto ) );
171 if ( !is_null( $mto ) ) {
172 wfDebug( __METHOD__
. ": Hook to BitmapHandlerTransform created an mto\n" );
173 $scaler = 'hookaborted';
178 # Handled by the hook above
179 $err = $mto->isError() ?
$mto : false;
182 $err = $this->transformImageMagick( $image, $scalerParams );
185 $err = $this->transformCustom( $image, $scalerParams );
188 $err = $this->transformImageMagickExt( $image, $scalerParams );
192 $err = $this->transformGd( $image, $scalerParams );
196 # Remove the file if a zero-byte thumbnail was created, or if there was an error
197 $removed = $this->removeBadFile( $dstPath, (bool)$err );
199 # transform returned MediaTransforError
201 } elseif ( $removed ) {
202 # Thumbnail was zero-byte and had to be removed
203 return new MediaTransformError( 'thumbnail_error',
204 $scalerParams['clientWidth'], $scalerParams['clientHeight'] );
208 return new ThumbnailImage( $image, $dstUrl, $scalerParams['clientWidth'],
209 $scalerParams['clientHeight'], $dstPath );
214 * Returns which scaler type should be used. Creates parent directories
215 * for $dstPath and returns 'client' on error
217 * @return string client,im,custom,gd
219 protected static function getScalerType( $dstPath, $checkDstPath = true ) {
220 global $wgUseImageResize, $wgUseImageMagick, $wgCustomConvertCommand;
222 if ( !$dstPath && $checkDstPath ) {
223 # No output path available, client side scaling only
225 } elseif ( !$wgUseImageResize ) {
227 } elseif ( $wgUseImageMagick ) {
229 } elseif ( $wgCustomConvertCommand ) {
231 } elseif ( function_exists( 'imagecreatetruecolor' ) ) {
233 } elseif ( class_exists( 'Imagick' ) ) {
242 * Get a ThumbnailImage that respresents an image that will be scaled
245 * @param $image File File associated with this thumbnail
246 * @param $params array Array with scaler params
247 * @return ThumbnailImage
249 * @fixme no rotation support
251 protected function getClientScalingThumbnailImage( $image, $params ) {
252 return new ThumbnailImage( $image, $image->getURL(),
253 $params['clientWidth'], $params['clientHeight'], null );
257 * Transform an image using ImageMagick
259 * @param $image File File associated with this thumbnail
260 * @param $params array Array with scaler params
262 * @return MediaTransformError Error object if error occured, false (=no error) otherwise
264 protected function transformImageMagick( $image, $params ) {
266 global $wgSharpenReductionThreshold, $wgSharpenParameter,
267 $wgMaxAnimatedGifArea,
268 $wgImageMagickTempDir, $wgImageMagickConvertCommand;
274 $animation_post = '';
276 if ( $params['mimeType'] == 'image/jpeg' ) {
277 $quality = "-quality 80"; // 80%
278 # Sharpening, see bug 6193
279 if ( ( $params['physicalWidth'] +
$params['physicalHeight'] )
280 / ( $params['srcWidth'] +
$params['srcHeight'] )
281 < $wgSharpenReductionThreshold ) {
282 $sharpen = "-sharpen " . wfEscapeShellArg( $wgSharpenParameter );
284 if ( version_compare( $this->getMagickVersion(), "6.5.6" ) >= 0 ) {
285 // JPEG decoder hint to reduce memory, available since IM 6.5.6-2
286 $decoderHint = "-define jpeg:size={$params['physicalDimensions']}";
289 } elseif ( $params['mimeType'] == 'image/png' ) {
290 $quality = "-quality 95"; // zlib 9, adaptive filtering
292 } elseif ( $params['mimeType'] == 'image/gif' ) {
293 if ( $this->getImageArea( $image ) > $wgMaxAnimatedGifArea ) {
294 // Extract initial frame only; we're so big it'll
295 // be a total drag. :P
298 } elseif ( $this->isAnimatedImage( $image ) ) {
299 // Coalesce is needed to scale animated GIFs properly (bug 1017).
300 $animation_pre = '-coalesce';
301 // We optimize the output, but -optimize is broken,
302 // use optimizeTransparency instead (bug 11822)
303 if ( version_compare( $this->getMagickVersion(), "6.3.5" ) >= 0 ) {
304 $animation_post = '-fuzz 5% -layers optimizeTransparency';
307 } elseif ( $params['mimeType'] == 'image/x-xcf' ) {
308 $animation_post = '-layers merge';
311 // Use one thread only, to avoid deadlock bugs on OOM
312 $env = array( 'OMP_NUM_THREADS' => 1 );
313 if ( strval( $wgImageMagickTempDir ) !== '' ) {
314 $env['MAGICK_TMPDIR'] = $wgImageMagickTempDir;
317 $rotation = $this->getRotation( $image );
318 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
321 wfEscapeShellArg( $wgImageMagickConvertCommand ) .
322 // Specify white background color, will be used for transparent images
323 // in Internet Explorer/Windows instead of default black.
324 " {$quality} -background white" .
326 wfEscapeShellArg( $this->escapeMagickInput( $params['srcPath'], $scene ) ) .
327 " {$animation_pre}" .
328 // For the -thumbnail option a "!" is needed to force exact size,
329 // or ImageMagick may decide your ratio is wrong and slice off
331 " -thumbnail " . wfEscapeShellArg( "{$width}x{$height}!" ) .
332 // Add the source url as a comment to the thumb, but don't add the flag if there's no comment
333 ( $params['comment'] !== ''
334 ?
" -set comment " . wfEscapeShellArg( $this->escapeMagickProperty( $params['comment'] ) )
336 " -depth 8 $sharpen " .
337 " -rotate -$rotation " .
338 " {$animation_post} " .
339 wfEscapeShellArg( $this->escapeMagickOutput( $params['dstPath'] ) ) . " 2>&1";
341 wfDebug( __METHOD__
. ": running ImageMagick: $cmd\n" );
342 wfProfileIn( 'convert' );
344 $err = wfShellExec( $cmd, $retval, $env );
345 wfProfileOut( 'convert' );
347 if ( $retval !== 0 ) {
348 $this->logErrorForExternalProcess( $retval, $err, $cmd );
349 return $this->getMediaTransformError( $params, $err );
352 return false; # No error
356 * Transform an image using the Imagick PHP extension
358 * @param $image File File associated with this thumbnail
359 * @param $params array Array with scaler params
361 * @return MediaTransformError Error object if error occured, false (=no error) otherwise
363 protected function transformImageMagickExt( $image, $params ) {
364 global $wgSharpenReductionThreshold, $wgSharpenParameter, $wgMaxAnimatedGifArea;
368 $im->readImage( $params['srcPath'] );
370 if ( $params['mimeType'] == 'image/jpeg' ) {
371 // Sharpening, see bug 6193
372 if ( ( $params['physicalWidth'] +
$params['physicalHeight'] )
373 / ( $params['srcWidth'] +
$params['srcHeight'] )
374 < $wgSharpenReductionThreshold ) {
375 // Hack, since $wgSharpenParamater is written specifically for the command line convert
376 list( $radius, $sigma ) = explode( 'x', $wgSharpenParameter );
377 $im->sharpenImage( $radius, $sigma );
379 $im->setCompressionQuality( 80 );
380 } elseif( $params['mimeType'] == 'image/png' ) {
381 $im->setCompressionQuality( 95 );
382 } elseif ( $params['mimeType'] == 'image/gif' ) {
383 if ( $this->getImageArea( $image ) > $wgMaxAnimatedGifArea ) {
384 // Extract initial frame only; we're so big it'll
385 // be a total drag. :P
386 $im->setImageScene( 0 );
387 } elseif ( $this->isAnimatedImage( $image ) ) {
388 // Coalesce is needed to scale animated GIFs properly (bug 1017).
389 $im = $im->coalesceImages();
393 $rotation = $this->getRotation( $image );
394 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
396 $im->setImageBackgroundColor( new ImagickPixel( 'white' ) );
398 // Call Imagick::thumbnailImage on each frame
399 foreach ( $im as $i => $frame ) {
400 if ( !$frame->thumbnailImage( $width, $height, /* fit */ false ) ) {
401 return $this->getMediaTransformError( $params, "Error scaling frame $i" );
404 $im->setImageDepth( 8 );
407 if ( !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) {
408 return $this->getMediaTransformError( $params, "Error rotating $rotation degrees" );
412 if ( $this->isAnimatedImage( $image ) ) {
413 wfDebug( __METHOD__
. ": Writing animated thumbnail\n" );
414 // This is broken somehow... can't find out how to fix it
415 $result = $im->writeImages( $params['dstPath'], true );
417 $result = $im->writeImage( $params['dstPath'] );
420 return $this->getMediaTransformError( $params,
421 "Unable to write thumbnail to {$params['dstPath']}" );
424 } catch ( ImagickException
$e ) {
425 return $this->getMediaTransformError( $params, $e->getMessage() );
433 * Transform an image using a custom command
435 * @param $image File File associated with this thumbnail
436 * @param $params array Array with scaler params
438 * @return MediaTransformError Error object if error occured, false (=no error) otherwise
440 protected function transformCustom( $image, $params ) {
441 # Use a custom convert command
442 global $wgCustomConvertCommand;
444 # Variables: %s %d %w %h
445 $src = wfEscapeShellArg( $params['srcPath'] );
446 $dst = wfEscapeShellArg( $params['dstPath'] );
447 $cmd = $wgCustomConvertCommand;
448 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
449 $cmd = str_replace( '%h', $params['physicalHeight'],
450 str_replace( '%w', $params['physicalWidth'], $cmd ) ); # Size
451 wfDebug( __METHOD__
. ": Running custom convert command $cmd\n" );
452 wfProfileIn( 'convert' );
454 $err = wfShellExec( $cmd, $retval );
455 wfProfileOut( 'convert' );
457 if ( $retval !== 0 ) {
458 $this->logErrorForExternalProcess( $retval, $err, $cmd );
459 return $this->getMediaTransformError( $params, $err );
461 return false; # No error
465 * Log an error that occured in an external process
471 protected function logErrorForExternalProcess( $retval, $err, $cmd ) {
472 wfDebugLog( 'thumbnail',
473 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
474 wfHostname(), $retval, trim( $err ), $cmd ) );
477 * Get a MediaTransformError with error 'thumbnail_error'
479 * @param $params array Parameter array as passed to the transform* functions
480 * @param $errMsg string Error message
481 * @return MediaTransformError
483 public function getMediaTransformError( $params, $errMsg ) {
484 return new MediaTransformError( 'thumbnail_error', $params['clientWidth'],
485 $params['clientHeight'], $errMsg );
489 * Transform an image using the built in GD library
491 * @param $image File File associated with this thumbnail
492 * @param $params array Array with scaler params
494 * @return MediaTransformError Error object if error occured, false (=no error) otherwise
496 protected function transformGd( $image, $params ) {
497 # Use PHP's builtin GD library functions.
499 # First find out what kind of file this is, and select the correct
500 # input routine for this.
503 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
504 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( __CLASS__
, 'imageJpegWrapper' ) ),
505 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
506 'image/vnd.wap.wbmp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
507 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
509 if ( !isset( $typemap[$params['mimeType']] ) ) {
510 $err = 'Image type not supported';
512 $errMsg = wfMsg( 'thumbnail_image-type' );
513 return $this->getMediaTransformError( $params, $errMsg );
515 list( $loader, $colorStyle, $saveType ) = $typemap[$params['mimeType']];
517 if ( !function_exists( $loader ) ) {
518 $err = "Incomplete GD library configuration: missing function $loader";
520 $errMsg = wfMsg( 'thumbnail_gd-library', $loader );
521 return $this->getMediaTransformError( $params, $errMsg );
524 if ( !file_exists( $params['srcPath'] ) ) {
525 $err = "File seems to be missing: {$params['srcPath']}";
527 $errMsg = wfMsg( 'thumbnail_image-missing', $params['srcPath'] );
528 return $this->getMediaTransformError( $params, $errMsg );
531 $src_image = call_user_func( $loader, $params['srcPath'] );
533 $rotation = function_exists( 'imagerotate' ) ?
$this->getRotation( $image ) : 0;
534 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
535 $dst_image = imagecreatetruecolor( $width, $height );
537 // Initialise the destination image to transparent instead of
538 // the default solid black, to support PNG and GIF transparency nicely
539 $background = imagecolorallocate( $dst_image, 0, 0, 0 );
540 imagecolortransparent( $dst_image, $background );
541 imagealphablending( $dst_image, false );
543 if ( $colorStyle == 'palette' ) {
544 // Don't resample for paletted GIF images.
545 // It may just uglify them, and completely breaks transparency.
546 imagecopyresized( $dst_image, $src_image,
549 imagesx( $src_image ), imagesy( $src_image ) );
551 imagecopyresampled( $dst_image, $src_image,
554 imagesx( $src_image ), imagesy( $src_image ) );
557 if ( $rotation %
360 != 0 && $rotation %
90 == 0 ) {
558 $rot_image = imagerotate( $dst_image, $rotation, 0 );
559 imagedestroy( $dst_image );
560 $dst_image = $rot_image;
563 imagesavealpha( $dst_image, true );
565 call_user_func( $saveType, $dst_image, $params['dstPath'] );
566 imagedestroy( $dst_image );
567 imagedestroy( $src_image );
569 return false; # No error
573 * Escape a string for ImageMagick's property input (e.g. -set -comment)
574 * See InterpretImageProperties() in magick/property.c
575 * @return mixed|string
577 function escapeMagickProperty( $s ) {
578 // Double the backslashes
579 $s = str_replace( '\\', '\\\\', $s );
580 // Double the percents
581 $s = str_replace( '%', '%%', $s );
582 // Escape initial - or @
583 if ( strlen( $s ) > 0 && ( $s[0] === '-' ||
$s[0] === '@' ) ) {
590 * Escape a string for ImageMagick's input filenames. See ExpandFilenames()
591 * and GetPathComponent() in magick/utility.c.
593 * This won't work with an initial ~ or @, so input files should be prefixed
594 * with the directory name.
596 * Glob character unescaping is broken in ImageMagick before 6.6.1-5, but
597 * it's broken in a way that doesn't involve trying to convert every file
598 * in a directory, so we're better off escaping and waiting for the bugfix
599 * to filter down to users.
601 * @param $path string The file path
602 * @param $scene string The scene specification, or false if there is none
605 function escapeMagickInput( $path, $scene = false ) {
606 # Die on initial metacharacters (caller should prepend path)
607 $firstChar = substr( $path, 0, 1 );
608 if ( $firstChar === '~' ||
$firstChar === '@' ) {
609 throw new MWException( __METHOD__
. ': cannot escape this path name' );
613 $path = preg_replace( '/[*?\[\]{}]/', '\\\\\0', $path );
615 return $this->escapeMagickPath( $path, $scene );
619 * Escape a string for ImageMagick's output filename. See
620 * InterpretImageFilename() in magick/image.c.
623 function escapeMagickOutput( $path, $scene = false ) {
624 $path = str_replace( '%', '%%', $path );
625 return $this->escapeMagickPath( $path, $scene );
629 * Armour a string against ImageMagick's GetPathComponent(). This is a
630 * helper function for escapeMagickInput() and escapeMagickOutput().
632 * @param $path string The file path
633 * @param $scene string The scene specification, or false if there is none
636 protected function escapeMagickPath( $path, $scene = false ) {
637 # Die on format specifiers (other than drive letters). The regex is
638 # meant to match all the formats you get from "convert -list format"
639 if ( preg_match( '/^([a-zA-Z0-9-]+):/', $path, $m ) ) {
640 if ( wfIsWindows() && is_dir( $m[0] ) ) {
641 // OK, it's a drive letter
642 // ImageMagick has a similar exception, see IsMagickConflict()
644 throw new MWException( __METHOD__
. ': unexpected colon character in path name' );
648 # If there are square brackets, add a do-nothing scene specification
649 # to force a literal interpretation
650 if ( $scene === false ) {
651 if ( strpos( $path, '[' ) !== false ) {
661 * Retrieve the version of the installed ImageMagick
662 * You can use PHPs version_compare() to use this value
663 * Value is cached for one hour.
664 * @return String representing the IM version.
666 protected function getMagickVersion() {
669 $cache = $wgMemc->get( "imagemagick-version" );
671 global $wgImageMagickConvertCommand;
672 $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . ' -version';
673 wfDebug( __METHOD__
. ": Running convert -version\n" );
675 $return = wfShellExec( $cmd, $retval );
676 $x = preg_match( '/Version: ImageMagick ([0-9]*\.[0-9]*\.[0-9]*)/', $return, $matches );
678 wfDebug( __METHOD__
. ": ImageMagick version check failed\n" );
681 $wgMemc->set( "imagemagick-version", $matches[1], 3600 );
687 static function imageJpegWrapper( $dst_image, $thumbPath ) {
688 imageinterlace( $dst_image );
689 imagejpeg( $dst_image, $thumbPath, 95 );
693 * On supporting image formats, try to read out the low-level orientation
694 * of the file and return the angle that the file needs to be rotated to
697 * This information is only useful when manipulating the original file;
698 * the width and height we normally work with is logical, and will match
699 * any produced output views.
701 * The base BitmapHandler doesn't understand any metadata formats, so this
702 * is left up to child classes to implement.
705 * @return int 0, 90, 180 or 270
707 public function getRotation( $file ) {
712 * Returns whether the current scaler supports rotation (im and gd do)
716 public static function canRotate() {
717 $scaler = self
::getScalerType( null, false );
720 # ImageMagick supports autorotation
723 # Imagick::rotateImage
726 # GD's imagerotate function is used to rotate images, but not
727 # all precompiled PHP versions have that function
728 return function_exists( 'imagerotate' );
730 # Other scalers don't support rotation
736 * Rerurns whether the file needs to be rendered. Returns true if the
737 * file requires rotation and we are able to rotate it.
742 public function mustRender( $file ) {
743 return self
::canRotate() && $this->getRotation( $file ) != 0;