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 'srcPath' => $image->getLocalRefPath(),
129 'dstPath' => $dstPath,
133 # Determine scaler type
134 $scaler = self
::getScalerType( $dstPath );
136 wfDebug( __METHOD__
. ": creating {$scalerParams['physicalDimensions']} thumbnail at $dstPath using scaler $scaler\n" );
138 if ( !$image->mustRender() &&
139 $scalerParams['physicalWidth'] == $scalerParams['srcWidth']
140 && $scalerParams['physicalHeight'] == $scalerParams['srcHeight'] ) {
142 # normaliseParams (or the user) wants us to return the unscaled image
143 wfDebug( __METHOD__
. ": returning unscaled image\n" );
144 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
148 if ( $scaler == 'client' ) {
149 # Client-side image scaling, use the source URL
150 # Using the destination URL in a TRANSFORM_LATER request would be incorrect
151 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
154 if ( $flags & self
::TRANSFORM_LATER
) {
155 wfDebug( __METHOD__
. ": Transforming later per flags.\n" );
156 return new ThumbnailImage( $image, $dstUrl, $scalerParams['clientWidth'],
157 $scalerParams['clientHeight'], $dstPath );
160 # Try to make a target path for the thumbnail
161 if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__
) ) {
162 wfDebug( __METHOD__
. ": Unable to create thumbnail destination directory, falling back to client scaling\n" );
163 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
168 wfRunHooks( 'BitmapHandlerTransform', array( $this, $image, &$scalerParams, &$mto ) );
169 if ( !is_null( $mto ) ) {
170 wfDebug( __METHOD__
. ": Hook to BitmapHandlerTransform created an mto\n" );
171 $scaler = 'hookaborted';
176 # Handled by the hook above
177 $err = $mto->isError() ?
$mto : false;
180 $err = $this->transformImageMagick( $image, $scalerParams );
183 $err = $this->transformCustom( $image, $scalerParams );
186 $err = $this->transformImageMagickExt( $image, $scalerParams );
190 $err = $this->transformGd( $image, $scalerParams );
194 # Remove the file if a zero-byte thumbnail was created, or if there was an error
195 $removed = $this->removeBadFile( $dstPath, (bool)$err );
197 # transform returned MediaTransforError
199 } elseif ( $removed ) {
200 # Thumbnail was zero-byte and had to be removed
201 return new MediaTransformError( 'thumbnail_error',
202 $scalerParams['clientWidth'], $scalerParams['clientHeight'] );
206 return new ThumbnailImage( $image, $dstUrl, $scalerParams['clientWidth'],
207 $scalerParams['clientHeight'], $dstPath );
212 * Returns which scaler type should be used. Creates parent directories
213 * for $dstPath and returns 'client' on error
215 * @return string client,im,custom,gd
217 protected static function getScalerType( $dstPath, $checkDstPath = true ) {
218 global $wgUseImageResize, $wgUseImageMagick, $wgCustomConvertCommand;
220 if ( !$dstPath && $checkDstPath ) {
221 # No output path available, client side scaling only
223 } elseif ( !$wgUseImageResize ) {
225 } elseif ( $wgUseImageMagick ) {
227 } elseif ( $wgCustomConvertCommand ) {
229 } elseif ( function_exists( 'imagecreatetruecolor' ) ) {
231 } elseif ( class_exists( 'Imagick' ) ) {
240 * Get a ThumbnailImage that respresents an image that will be scaled
243 * @param $image File File associated with this thumbnail
244 * @param $params array Array with scaler params
245 * @return ThumbnailImage
247 * @fixme no rotation support
249 protected function getClientScalingThumbnailImage( $image, $params ) {
250 return new ThumbnailImage( $image, $image->getURL(),
251 $params['clientWidth'], $params['clientHeight'], $params['srcPath'] );
255 * Transform an image using ImageMagick
257 * @param $image File File associated with this thumbnail
258 * @param $params array Array with scaler params
260 * @return MediaTransformError Error object if error occured, false (=no error) otherwise
262 protected function transformImageMagick( $image, $params ) {
264 global $wgSharpenReductionThreshold, $wgSharpenParameter,
265 $wgMaxAnimatedGifArea,
266 $wgImageMagickTempDir, $wgImageMagickConvertCommand;
272 $animation_post = '';
274 if ( $params['mimeType'] == 'image/jpeg' ) {
275 $quality = "-quality 80"; // 80%
276 # Sharpening, see bug 6193
277 if ( ( $params['physicalWidth'] +
$params['physicalHeight'] )
278 / ( $params['srcWidth'] +
$params['srcHeight'] )
279 < $wgSharpenReductionThreshold ) {
280 $sharpen = "-sharpen " . wfEscapeShellArg( $wgSharpenParameter );
282 if ( version_compare( $this->getMagickVersion(), "6.5.6" ) >= 0 ) {
283 // JPEG decoder hint to reduce memory, available since IM 6.5.6-2
284 $decoderHint = "-define jpeg:size={$params['physicalDimensions']}";
287 } elseif ( $params['mimeType'] == 'image/png' ) {
288 $quality = "-quality 95"; // zlib 9, adaptive filtering
290 } elseif ( $params['mimeType'] == 'image/gif' ) {
291 if ( $this->getImageArea( $image ) > $wgMaxAnimatedGifArea ) {
292 // Extract initial frame only; we're so big it'll
293 // be a total drag. :P
296 } elseif ( $this->isAnimatedImage( $image ) ) {
297 // Coalesce is needed to scale animated GIFs properly (bug 1017).
298 $animation_pre = '-coalesce';
299 // We optimize the output, but -optimize is broken,
300 // use optimizeTransparency instead (bug 11822)
301 if ( version_compare( $this->getMagickVersion(), "6.3.5" ) >= 0 ) {
302 $animation_post = '-fuzz 5% -layers optimizeTransparency';
305 } elseif ( $params['mimeType'] == 'image/x-xcf' ) {
306 $animation_post = '-layers merge';
309 // Use one thread only, to avoid deadlock bugs on OOM
310 $env = array( 'OMP_NUM_THREADS' => 1 );
311 if ( strval( $wgImageMagickTempDir ) !== '' ) {
312 $env['MAGICK_TMPDIR'] = $wgImageMagickTempDir;
315 $rotation = $this->getRotation( $image );
316 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
319 wfEscapeShellArg( $wgImageMagickConvertCommand ) .
320 // Specify white background color, will be used for transparent images
321 // in Internet Explorer/Windows instead of default black.
322 " {$quality} -background white" .
324 wfEscapeShellArg( $this->escapeMagickInput( $params['srcPath'], $scene ) ) .
325 " {$animation_pre}" .
326 // For the -thumbnail option a "!" is needed to force exact size,
327 // or ImageMagick may decide your ratio is wrong and slice off
329 " -thumbnail " . wfEscapeShellArg( "{$width}x{$height}!" ) .
330 // Add the source url as a comment to the thumb, but don't add the flag if there's no comment
331 ( $params['comment'] !== ''
332 ?
" -set comment " . wfEscapeShellArg( $this->escapeMagickProperty( $params['comment'] ) )
334 " -depth 8 $sharpen " .
335 " -rotate -$rotation " .
336 " {$animation_post} " .
337 wfEscapeShellArg( $this->escapeMagickOutput( $params['dstPath'] ) ) . " 2>&1";
339 wfDebug( __METHOD__
. ": running ImageMagick: $cmd\n" );
340 wfProfileIn( 'convert' );
342 $err = wfShellExec( $cmd, $retval, $env );
343 wfProfileOut( 'convert' );
345 if ( $retval !== 0 ) {
346 $this->logErrorForExternalProcess( $retval, $err, $cmd );
347 return $this->getMediaTransformError( $params, $err );
350 return false; # No error
354 * Transform an image using the Imagick PHP extension
356 * @param $image File File associated with this thumbnail
357 * @param $params array Array with scaler params
359 * @return MediaTransformError Error object if error occured, false (=no error) otherwise
361 protected function transformImageMagickExt( $image, $params ) {
362 global $wgSharpenReductionThreshold, $wgSharpenParameter, $wgMaxAnimatedGifArea;
366 $im->readImage( $params['srcPath'] );
368 if ( $params['mimeType'] == 'image/jpeg' ) {
369 // Sharpening, see bug 6193
370 if ( ( $params['physicalWidth'] +
$params['physicalHeight'] )
371 / ( $params['srcWidth'] +
$params['srcHeight'] )
372 < $wgSharpenReductionThreshold ) {
373 // Hack, since $wgSharpenParamater is written specifically for the command line convert
374 list( $radius, $sigma ) = explode( 'x', $wgSharpenParameter );
375 $im->sharpenImage( $radius, $sigma );
377 $im->setCompressionQuality( 80 );
378 } elseif( $params['mimeType'] == 'image/png' ) {
379 $im->setCompressionQuality( 95 );
380 } elseif ( $params['mimeType'] == 'image/gif' ) {
381 if ( $this->getImageArea( $image ) > $wgMaxAnimatedGifArea ) {
382 // Extract initial frame only; we're so big it'll
383 // be a total drag. :P
384 $im->setImageScene( 0 );
385 } elseif ( $this->isAnimatedImage( $image ) ) {
386 // Coalesce is needed to scale animated GIFs properly (bug 1017).
387 $im = $im->coalesceImages();
391 $rotation = $this->getRotation( $image );
392 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
394 $im->setImageBackgroundColor( new ImagickPixel( 'white' ) );
396 // Call Imagick::thumbnailImage on each frame
397 foreach ( $im as $i => $frame ) {
398 if ( !$frame->thumbnailImage( $width, $height, /* fit */ false ) ) {
399 return $this->getMediaTransformError( $params, "Error scaling frame $i" );
402 $im->setImageDepth( 8 );
405 if ( !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) {
406 return $this->getMediaTransformError( $params, "Error rotating $rotation degrees" );
410 if ( $this->isAnimatedImage( $image ) ) {
411 wfDebug( __METHOD__
. ": Writing animated thumbnail\n" );
412 // This is broken somehow... can't find out how to fix it
413 $result = $im->writeImages( $params['dstPath'], true );
415 $result = $im->writeImage( $params['dstPath'] );
418 return $this->getMediaTransformError( $params,
419 "Unable to write thumbnail to {$params['dstPath']}" );
422 } catch ( ImagickException
$e ) {
423 return $this->getMediaTransformError( $params, $e->getMessage() );
431 * Transform an image using a custom command
433 * @param $image File File associated with this thumbnail
434 * @param $params array Array with scaler params
436 * @return MediaTransformError Error object if error occured, false (=no error) otherwise
438 protected function transformCustom( $image, $params ) {
439 # Use a custom convert command
440 global $wgCustomConvertCommand;
442 # Variables: %s %d %w %h
443 $src = wfEscapeShellArg( $params['srcPath'] );
444 $dst = wfEscapeShellArg( $params['dstPath'] );
445 $cmd = $wgCustomConvertCommand;
446 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
447 $cmd = str_replace( '%h', $params['physicalHeight'],
448 str_replace( '%w', $params['physicalWidth'], $cmd ) ); # Size
449 wfDebug( __METHOD__
. ": Running custom convert command $cmd\n" );
450 wfProfileIn( 'convert' );
452 $err = wfShellExec( $cmd, $retval );
453 wfProfileOut( 'convert' );
455 if ( $retval !== 0 ) {
456 $this->logErrorForExternalProcess( $retval, $err, $cmd );
457 return $this->getMediaTransformError( $params, $err );
459 return false; # No error
463 * Log an error that occured in an external process
469 protected function logErrorForExternalProcess( $retval, $err, $cmd ) {
470 wfDebugLog( 'thumbnail',
471 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
472 wfHostname(), $retval, trim( $err ), $cmd ) );
475 * Get a MediaTransformError with error 'thumbnail_error'
477 * @param $params array Parameter array as passed to the transform* functions
478 * @param $errMsg string Error message
479 * @return MediaTransformError
481 public function getMediaTransformError( $params, $errMsg ) {
482 return new MediaTransformError( 'thumbnail_error', $params['clientWidth'],
483 $params['clientHeight'], $errMsg );
487 * Transform an image using the built in GD library
489 * @param $image File File associated with this thumbnail
490 * @param $params array Array with scaler params
492 * @return MediaTransformError Error object if error occured, false (=no error) otherwise
494 protected function transformGd( $image, $params ) {
495 # Use PHP's builtin GD library functions.
497 # First find out what kind of file this is, and select the correct
498 # input routine for this.
501 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
502 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( __CLASS__
, 'imageJpegWrapper' ) ),
503 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
504 'image/vnd.wap.wbmp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
505 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
507 if ( !isset( $typemap[$params['mimeType']] ) ) {
508 $err = 'Image type not supported';
510 $errMsg = wfMsg ( 'thumbnail_image-type' );
511 return $this->getMediaTransformError( $params, $errMsg );
513 list( $loader, $colorStyle, $saveType ) = $typemap[$params['mimeType']];
515 if ( !function_exists( $loader ) ) {
516 $err = "Incomplete GD library configuration: missing function $loader";
518 $errMsg = wfMsg ( 'thumbnail_gd-library', $loader );
519 return $this->getMediaTransformError( $params, $errMsg );
522 if ( !file_exists( $params['srcPath'] ) ) {
523 $err = "File seems to be missing: {$params['srcPath']}";
525 $errMsg = wfMsg ( 'thumbnail_image-missing', $params['srcPath'] );
526 return $this->getMediaTransformError( $params, $errMsg );
529 $src_image = call_user_func( $loader, $params['srcPath'] );
531 $rotation = function_exists( 'imagerotate' ) ?
$this->getRotation( $image ) : 0;
532 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
533 $dst_image = imagecreatetruecolor( $width, $height );
535 // Initialise the destination image to transparent instead of
536 // the default solid black, to support PNG and GIF transparency nicely
537 $background = imagecolorallocate( $dst_image, 0, 0, 0 );
538 imagecolortransparent( $dst_image, $background );
539 imagealphablending( $dst_image, false );
541 if ( $colorStyle == 'palette' ) {
542 // Don't resample for paletted GIF images.
543 // It may just uglify them, and completely breaks transparency.
544 imagecopyresized( $dst_image, $src_image,
547 imagesx( $src_image ), imagesy( $src_image ) );
549 imagecopyresampled( $dst_image, $src_image,
552 imagesx( $src_image ), imagesy( $src_image ) );
555 if ( $rotation %
360 != 0 && $rotation %
90 == 0 ) {
556 $rot_image = imagerotate( $dst_image, $rotation, 0 );
557 imagedestroy( $dst_image );
558 $dst_image = $rot_image;
561 imagesavealpha( $dst_image, true );
563 call_user_func( $saveType, $dst_image, $params['dstPath'] );
564 imagedestroy( $dst_image );
565 imagedestroy( $src_image );
567 return false; # No error
571 * Escape a string for ImageMagick's property input (e.g. -set -comment)
572 * See InterpretImageProperties() in magick/property.c
574 function escapeMagickProperty( $s ) {
575 // Double the backslashes
576 $s = str_replace( '\\', '\\\\', $s );
577 // Double the percents
578 $s = str_replace( '%', '%%', $s );
579 // Escape initial - or @
580 if ( strlen( $s ) > 0 && ( $s[0] === '-' ||
$s[0] === '@' ) ) {
587 * Escape a string for ImageMagick's input filenames. See ExpandFilenames()
588 * and GetPathComponent() in magick/utility.c.
590 * This won't work with an initial ~ or @, so input files should be prefixed
591 * with the directory name.
593 * Glob character unescaping is broken in ImageMagick before 6.6.1-5, but
594 * it's broken in a way that doesn't involve trying to convert every file
595 * in a directory, so we're better off escaping and waiting for the bugfix
596 * to filter down to users.
598 * @param $path string The file path
599 * @param $scene string The scene specification, or false if there is none
601 function escapeMagickInput( $path, $scene = false ) {
602 # Die on initial metacharacters (caller should prepend path)
603 $firstChar = substr( $path, 0, 1 );
604 if ( $firstChar === '~' ||
$firstChar === '@' ) {
605 throw new MWException( __METHOD__
. ': cannot escape this path name' );
609 $path = preg_replace( '/[*?\[\]{}]/', '\\\\\0', $path );
611 return $this->escapeMagickPath( $path, $scene );
615 * Escape a string for ImageMagick's output filename. See
616 * InterpretImageFilename() in magick/image.c.
618 function escapeMagickOutput( $path, $scene = false ) {
619 $path = str_replace( '%', '%%', $path );
620 return $this->escapeMagickPath( $path, $scene );
624 * Armour a string against ImageMagick's GetPathComponent(). This is a
625 * helper function for escapeMagickInput() and escapeMagickOutput().
627 * @param $path string The file path
628 * @param $scene string The scene specification, or false if there is none
630 protected function escapeMagickPath( $path, $scene = false ) {
631 # Die on format specifiers (other than drive letters). The regex is
632 # meant to match all the formats you get from "convert -list format"
633 if ( preg_match( '/^([a-zA-Z0-9-]+):/', $path, $m ) ) {
634 if ( wfIsWindows() && is_dir( $m[0] ) ) {
635 // OK, it's a drive letter
636 // ImageMagick has a similar exception, see IsMagickConflict()
638 throw new MWException( __METHOD__
. ': unexpected colon character in path name' );
642 # If there are square brackets, add a do-nothing scene specification
643 # to force a literal interpretation
644 if ( $scene === false ) {
645 if ( strpos( $path, '[' ) !== false ) {
655 * Retrieve the version of the installed ImageMagick
656 * You can use PHPs version_compare() to use this value
657 * Value is cached for one hour.
658 * @return String representing the IM version.
660 protected function getMagickVersion() {
663 $cache = $wgMemc->get( "imagemagick-version" );
665 global $wgImageMagickConvertCommand;
666 $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . ' -version';
667 wfDebug( __METHOD__
. ": Running convert -version\n" );
669 $return = wfShellExec( $cmd, $retval );
670 $x = preg_match( '/Version: ImageMagick ([0-9]*\.[0-9]*\.[0-9]*)/', $return, $matches );
672 wfDebug( __METHOD__
. ": ImageMagick version check failed\n" );
675 $wgMemc->set( "imagemagick-version", $matches[1], 3600 );
681 static function imageJpegWrapper( $dst_image, $thumbPath ) {
682 imageinterlace( $dst_image );
683 imagejpeg( $dst_image, $thumbPath, 95 );
687 * On supporting image formats, try to read out the low-level orientation
688 * of the file and return the angle that the file needs to be rotated to
691 * This information is only useful when manipulating the original file;
692 * the width and height we normally work with is logical, and will match
693 * any produced output views.
695 * The base BitmapHandler doesn't understand any metadata formats, so this
696 * is left up to child classes to implement.
699 * @return int 0, 90, 180 or 270
701 public function getRotation( $file ) {
706 * Returns whether the current scaler supports rotation (im and gd do)
710 public static function canRotate() {
711 $scaler = self
::getScalerType( null, false );
714 # ImageMagick supports autorotation
717 # Imagick::rotateImage
720 # GD's imagerotate function is used to rotate images, but not
721 # all precompiled PHP versions have that function
722 return function_exists( 'imagerotate' );
724 # Other scalers don't support rotation
730 * Rerurns whether the file needs to be rendered. Returns true if the
731 * file requires rotation and we are able to rotate it.
736 public function mustRender( $file ) {
737 return self
::canRotate() && $this->getRotation( $file ) != 0;