3 * Generic handler for bitmap images
10 * Generic handler for bitmap images
14 class BitmapHandler
extends ImageHandler
{
18 * @param $params array Transform parameters. Entries with the keys 'width'
19 * and 'height' are the respective screen width and height, while the keys
20 * 'physicalWidth' and 'physicalHeight' indicate the thumbnail dimensions.
23 function normaliseParams( $image, &$params ) {
25 if ( !parent
::normaliseParams( $image, $params ) ) {
29 $mimeType = $image->getMimeType();
30 # Obtain the source, pre-rotation dimensions
31 $srcWidth = $image->getWidth( $params['page'] );
32 $srcHeight = $image->getHeight( $params['page'] );
34 # Don't make an image bigger than the source
35 if ( $params['physicalWidth'] >= $srcWidth ) {
36 $params['physicalWidth'] = $srcWidth;
37 $params['physicalHeight'] = $srcHeight;
39 # Skip scaling limit checks if no scaling is required
40 # due to requested size being bigger than source.
41 if ( !$image->mustRender() ) {
50 * Check if the file is smaller than the maximum image area for
51 * thumbnailing. Check will always pass if the scaler is 'hookaborted' or
52 * if the scaler is 'im' and the mime type is 'image/jpeg'
55 * @param string $scaler
57 function checkImageArea( $image, $scaler ) {
58 global $wgMaxImageArea;
59 # Don't thumbnail an image so big that it will fill hard drives and send servers into swap
60 # JPEG has the handy property of allowing thumbnailing without full decompression, so we make
61 # an exception for it.
64 if ( $image->getMimeType() == 'image/jpeg' && $scaler == 'im' )
66 # ImageMagick can efficiently downsize jpg images without loading
67 # the entire file in memory
71 if ( $scaler == 'hookaborted' )
73 # If a hook wants to transform the image, it is responsible for
74 # checking the image size, so abort here
79 return $this->getImageArea( $image, $image->getWidth(), $image->getHeight() ) <= $wgMaxImageArea;
84 * Extracts the width/height if the image will be scaled before rotating
86 * This will match the physical size/aspect ratio of the original image
87 * prior to application of the rotation -- so for a portrait image that's
88 * stored as raw landscape with 90-degress rotation, the resulting size
89 * will be wider than it is tall.
91 * @param $params array Parameters as returned by normaliseParams
92 * @param $rotation int The rotation angle that will be applied
93 * @return array ($width, $height) array
95 public function extractPreRotationDimensions( $params, $rotation ) {
96 if ( $rotation == 90 ||
$rotation == 270 ) {
97 # We'll resize before rotation, so swap the dimensions again
98 $width = $params['physicalHeight'];
99 $height = $params['physicalWidth'];
101 $width = $params['physicalWidth'];
102 $height = $params['physicalHeight'];
104 return array( $width, $height );
108 // Function that returns the number of pixels to be thumbnailed.
109 // Intended for animated GIFs to multiply by the number of frames.
110 function getImageArea( $image, $width, $height ) {
111 return $width * $height;
120 * @return MediaTransformError|ThumbnailImage|TransformParameterError
122 function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
123 if ( !$this->normaliseParams( $image, $params ) ) {
124 return new TransformParameterError( $params );
126 # Create a parameter array to pass to the scaler
127 $scalerParams = array(
128 # The size to which the image will be resized
129 'physicalWidth' => $params['physicalWidth'],
130 'physicalHeight' => $params['physicalHeight'],
131 'physicalDimensions' => "{$params['physicalWidth']}x{$params['physicalHeight']}",
132 # The size of the image on the page
133 'clientWidth' => $params['width'],
134 'clientHeight' => $params['height'],
135 # Comment as will be added to the EXIF of the thumbnail
136 'comment' => isset( $params['descriptionUrl'] ) ?
137 "File source: {$params['descriptionUrl']}" : '',
138 # Properties of the original image
139 'srcWidth' => $image->getWidth(),
140 'srcHeight' => $image->getHeight(),
141 'mimeType' => $image->getMimeType(),
142 'srcPath' => $image->getPath(),
143 'dstPath' => $dstPath,
147 wfDebug( __METHOD__
. ": creating {$scalerParams['physicalDimensions']} thumbnail at $dstPath\n" );
149 if ( !$image->mustRender() &&
150 $scalerParams['physicalWidth'] == $scalerParams['srcWidth']
151 && $scalerParams['physicalHeight'] == $scalerParams['srcHeight'] ) {
153 # normaliseParams (or the user) wants us to return the unscaled image
154 wfDebug( __METHOD__
. ": returning unscaled image\n" );
155 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
158 # Determine scaler type
159 $scaler = self
::getScalerType( $dstPath );
160 wfDebug( __METHOD__
. ": scaler $scaler\n" );
162 if ( $scaler == 'client' ) {
163 # Client-side image scaling, use the source URL
164 # Using the destination URL in a TRANSFORM_LATER request would be incorrect
165 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
168 if ( $flags & self
::TRANSFORM_LATER
) {
169 wfDebug( __METHOD__
. ": Transforming later per flags.\n" );
170 return new ThumbnailImage( $image, $dstUrl, $scalerParams['clientWidth'],
171 $scalerParams['clientHeight'], $dstPath );
174 # Try to make a target path for the thumbnail
175 if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__
) ) {
176 wfDebug( __METHOD__
. ": Unable to create thumbnail destination directory, falling back to client scaling\n" );
177 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
182 wfRunHooks( 'BitmapHandlerTransform', array( $this, $image, &$scalerParams, &$mto ) );
183 if ( !is_null( $mto ) ) {
184 wfDebug( __METHOD__
. ": Hook to BitmapHandlerTransform created an mto\n" );
185 $scaler = 'hookaborted';
188 # Check max image area
189 if ( !$this->checkImageArea( $image, $scaler ) )
191 return new TransformParameterError( $params );
196 # Handled by the hook above
197 $err = $mto->isError() ?
$mto : false;
200 $err = $this->transformImageMagick( $image, $scalerParams );
203 $err = $this->transformCustom( $image, $scalerParams );
206 $err = $this->transformImageMagickExt( $image, $scalerParams );
210 $err = $this->transformGd( $image, $scalerParams );
214 # Remove the file if a zero-byte thumbnail was created, or if there was an error
215 $removed = $this->removeBadFile( $dstPath, (bool)$err );
217 # transform returned MediaTransforError
219 } elseif ( $removed ) {
220 # Thumbnail was zero-byte and had to be removed
221 return new MediaTransformError( 'thumbnail_error',
222 $scalerParams['clientWidth'], $scalerParams['clientHeight'] );
226 return new ThumbnailImage( $image, $dstUrl, $scalerParams['clientWidth'],
227 $scalerParams['clientHeight'], $dstPath );
232 * Returns which scaler type should be used. Creates parent directories
233 * for $dstPath and returns 'client' on error
235 * @return string client,im,custom,gd
237 protected static function getScalerType( $dstPath, $checkDstPath = true ) {
238 global $wgUseImageResize, $wgUseImageMagick, $wgCustomConvertCommand;
240 if ( !$dstPath && $checkDstPath ) {
241 # No output path available, client side scaling only
243 } elseif ( !$wgUseImageResize ) {
245 } elseif ( $wgUseImageMagick ) {
247 } elseif ( $wgCustomConvertCommand ) {
249 } elseif ( function_exists( 'imagecreatetruecolor' ) ) {
251 } elseif ( class_exists( 'Imagick' ) ) {
260 * Get a ThumbnailImage that respresents an image that will be scaled
263 * @param $image File File associated with this thumbnail
264 * @param $params array Array with scaler params
265 * @return ThumbnailImage
267 * @fixme no rotation support
269 protected function getClientScalingThumbnailImage( $image, $params ) {
270 return new ThumbnailImage( $image, $image->getURL(),
271 $params['clientWidth'], $params['clientHeight'], $params['srcPath'] );
275 * Transform an image using ImageMagick
277 * @param $image File File associated with this thumbnail
278 * @param $params array Array with scaler params
280 * @return MediaTransformError Error object if error occured, false (=no error) otherwise
282 protected function transformImageMagick( $image, $params ) {
284 global $wgSharpenReductionThreshold, $wgSharpenParameter,
285 $wgMaxAnimatedGifArea,
286 $wgImageMagickTempDir, $wgImageMagickConvertCommand;
292 $animation_post = '';
294 if ( $params['mimeType'] == 'image/jpeg' ) {
295 $quality = "-quality 80"; // 80%
296 # Sharpening, see bug 6193
297 if ( ( $params['physicalWidth'] +
$params['physicalHeight'] )
298 / ( $params['srcWidth'] +
$params['srcHeight'] )
299 < $wgSharpenReductionThreshold ) {
300 $sharpen = "-sharpen " . wfEscapeShellArg( $wgSharpenParameter );
302 // JPEG decoder hint to reduce memory, available since IM 6.5.6-2
303 $decoderHint = "-define jpeg:size={$params['physicalDimensions']}";
305 } elseif ( $params['mimeType'] == 'image/png' ) {
306 $quality = "-quality 95"; // zlib 9, adaptive filtering
308 } elseif ( $params['mimeType'] == 'image/gif' ) {
309 if ( $this->getImageArea( $image, $params['srcWidth'],
310 $params['srcHeight'] ) > $wgMaxAnimatedGifArea ) {
311 // Extract initial frame only; we're so big it'll
312 // be a total drag. :P
315 } elseif ( $this->isAnimatedImage( $image ) ) {
316 // Coalesce is needed to scale animated GIFs properly (bug 1017).
317 $animation_pre = '-coalesce';
318 // We optimize the output, but -optimize is broken,
319 // use optimizeTransparency instead (bug 11822)
320 if ( version_compare( $this->getMagickVersion(), "6.3.5" ) >= 0 ) {
321 $animation_post = '-fuzz 5% -layers optimizeTransparency';
326 // Use one thread only, to avoid deadlock bugs on OOM
327 $env = array( 'OMP_NUM_THREADS' => 1 );
328 if ( strval( $wgImageMagickTempDir ) !== '' ) {
329 $env['MAGICK_TMPDIR'] = $wgImageMagickTempDir;
332 $rotation = $this->getRotation( $image );
333 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
336 wfEscapeShellArg( $wgImageMagickConvertCommand ) .
337 // Specify white background color, will be used for transparent images
338 // in Internet Explorer/Windows instead of default black.
339 " {$quality} -background white" .
341 wfEscapeShellArg( $this->escapeMagickInput( $params['srcPath'], $scene ) ) .
342 " {$animation_pre}" .
343 // For the -thumbnail option a "!" is needed to force exact size,
344 // or ImageMagick may decide your ratio is wrong and slice off
346 " -thumbnail " . wfEscapeShellArg( "{$width}x{$height}!" ) .
347 // Add the source url as a comment to the thumb, but don't add the flag if there's no comment
348 ( $params['comment'] !== ''
349 ?
" -set comment " . wfEscapeShellArg( $this->escapeMagickProperty( $params['comment'] ) )
351 " -depth 8 $sharpen " .
352 " -rotate -$rotation " .
353 " {$animation_post} " .
354 wfEscapeShellArg( $this->escapeMagickOutput( $params['dstPath'] ) ) . " 2>&1";
356 wfDebug( __METHOD__
. ": running ImageMagick: $cmd\n" );
357 wfProfileIn( 'convert' );
359 $err = wfShellExec( $cmd, $retval, $env );
360 wfProfileOut( 'convert' );
362 if ( $retval !== 0 ) {
363 $this->logErrorForExternalProcess( $retval, $err, $cmd );
364 return $this->getMediaTransformError( $params, $err );
367 return false; # No error
371 * Transform an image using the Imagick PHP extension
373 * @param $image File File associated with this thumbnail
374 * @param $params array Array with scaler params
376 * @return MediaTransformError Error object if error occured, false (=no error) otherwise
378 protected function transformImageMagickExt( $image, $params ) {
379 global $wgSharpenReductionThreshold, $wgSharpenParameter, $wgMaxAnimatedGifArea;
383 $im->readImage( $params['srcPath'] );
385 if ( $params['mimeType'] == 'image/jpeg' ) {
386 // Sharpening, see bug 6193
387 if ( ( $params['physicalWidth'] +
$params['physicalHeight'] )
388 / ( $params['srcWidth'] +
$params['srcHeight'] )
389 < $wgSharpenReductionThreshold ) {
390 // Hack, since $wgSharpenParamater is written specifically for the command line convert
391 list( $radius, $sigma ) = explode( 'x', $wgSharpenParameter );
392 $im->sharpenImage( $radius, $sigma );
394 $im->setCompressionQuality( 80 );
395 } elseif( $params['mimeType'] == 'image/png' ) {
396 $im->setCompressionQuality( 95 );
397 } elseif ( $params['mimeType'] == 'image/gif' ) {
398 if ( $this->getImageArea( $image, $params['srcWidth'],
399 $params['srcHeight'] ) > $wgMaxAnimatedGifArea ) {
400 // Extract initial frame only; we're so big it'll
401 // be a total drag. :P
402 $im->setImageScene( 0 );
403 } elseif ( $this->isAnimatedImage( $image ) ) {
404 // Coalesce is needed to scale animated GIFs properly (bug 1017).
405 $im = $im->coalesceImages();
409 $rotation = $this->getRotation( $image );
410 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
412 $im->setImageBackgroundColor( new ImagickPixel( 'white' ) );
414 // Call Imagick::thumbnailImage on each frame
415 foreach ( $im as $i => $frame ) {
416 if ( !$frame->thumbnailImage( $width, $height, /* fit */ false ) ) {
417 return $this->getMediaTransformError( $params, "Error scaling frame $i" );
420 $im->setImageDepth( 8 );
423 if ( !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) {
424 return $this->getMediaTransformError( $params, "Error rotating $rotation degrees" );
428 if ( $this->isAnimatedImage( $image ) ) {
429 wfDebug( __METHOD__
. ": Writing animated thumbnail\n" );
430 // This is broken somehow... can't find out how to fix it
431 $result = $im->writeImages( $params['dstPath'], true );
433 $result = $im->writeImage( $params['dstPath'] );
436 return $this->getMediaTransformError( $params,
437 "Unable to write thumbnail to {$params['dstPath']}" );
440 } catch ( ImagickException
$e ) {
441 return $this->getMediaTransformError( $params, $e->getMessage() );
449 * Transform an image using a custom command
451 * @param $image File File associated with this thumbnail
452 * @param $params array Array with scaler params
454 * @return MediaTransformError Error object if error occured, false (=no error) otherwise
456 protected function transformCustom( $image, $params ) {
457 # Use a custom convert command
458 global $wgCustomConvertCommand;
460 # Variables: %s %d %w %h
461 $src = wfEscapeShellArg( $params['srcPath'] );
462 $dst = wfEscapeShellArg( $params['dstPath'] );
463 $cmd = $wgCustomConvertCommand;
464 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
465 $cmd = str_replace( '%h', $params['physicalHeight'],
466 str_replace( '%w', $params['physicalWidth'], $cmd ) ); # Size
467 wfDebug( __METHOD__
. ": Running custom convert command $cmd\n" );
468 wfProfileIn( 'convert' );
470 $err = wfShellExec( $cmd, $retval );
471 wfProfileOut( 'convert' );
473 if ( $retval !== 0 ) {
474 $this->logErrorForExternalProcess( $retval, $err, $cmd );
475 return $this->getMediaTransformError( $params, $err );
477 return false; # No error
481 * Log an error that occured in an external process
487 protected function logErrorForExternalProcess( $retval, $err, $cmd ) {
488 wfDebugLog( 'thumbnail',
489 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
490 wfHostname(), $retval, trim( $err ), $cmd ) );
493 * Get a MediaTransformError with error 'thumbnail_error'
495 * @param $params array Parameter array as passed to the transform* functions
496 * @param $errMsg string Error message
497 * @return MediaTransformError
499 public function getMediaTransformError( $params, $errMsg ) {
500 return new MediaTransformError( 'thumbnail_error', $params['clientWidth'],
501 $params['clientHeight'], $errMsg );
505 * Transform an image using the built in GD library
507 * @param $image File File associated with this thumbnail
508 * @param $params array Array with scaler params
510 * @return MediaTransformError Error object if error occured, false (=no error) otherwise
512 protected function transformGd( $image, $params ) {
513 # Use PHP's builtin GD library functions.
515 # First find out what kind of file this is, and select the correct
516 # input routine for this.
519 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
520 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( __CLASS__
, 'imageJpegWrapper' ) ),
521 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
522 'image/vnd.wap.wbmp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
523 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
525 if ( !isset( $typemap[$params['mimeType']] ) ) {
526 $err = 'Image type not supported';
528 $errMsg = wfMsg ( 'thumbnail_image-type' );
529 return $this->getMediaTransformError( $params, $errMsg );
531 list( $loader, $colorStyle, $saveType ) = $typemap[$params['mimeType']];
533 if ( !function_exists( $loader ) ) {
534 $err = "Incomplete GD library configuration: missing function $loader";
536 $errMsg = wfMsg ( 'thumbnail_gd-library', $loader );
537 return $this->getMediaTransformError( $params, $errMsg );
540 if ( !file_exists( $params['srcPath'] ) ) {
541 $err = "File seems to be missing: {$params['srcPath']}";
543 $errMsg = wfMsg ( 'thumbnail_image-missing', $params['srcPath'] );
544 return $this->getMediaTransformError( $params, $errMsg );
547 $src_image = call_user_func( $loader, $params['srcPath'] );
549 $rotation = function_exists( 'imagerotate' ) ?
$this->getRotation( $image ) : 0;
550 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
551 $dst_image = imagecreatetruecolor( $width, $height );
553 // Initialise the destination image to transparent instead of
554 // the default solid black, to support PNG and GIF transparency nicely
555 $background = imagecolorallocate( $dst_image, 0, 0, 0 );
556 imagecolortransparent( $dst_image, $background );
557 imagealphablending( $dst_image, false );
559 if ( $colorStyle == 'palette' ) {
560 // Don't resample for paletted GIF images.
561 // It may just uglify them, and completely breaks transparency.
562 imagecopyresized( $dst_image, $src_image,
565 imagesx( $src_image ), imagesy( $src_image ) );
567 imagecopyresampled( $dst_image, $src_image,
570 imagesx( $src_image ), imagesy( $src_image ) );
573 if ( $rotation %
360 != 0 && $rotation %
90 == 0 ) {
574 $rot_image = imagerotate( $dst_image, $rotation, 0 );
575 imagedestroy( $dst_image );
576 $dst_image = $rot_image;
579 imagesavealpha( $dst_image, true );
581 call_user_func( $saveType, $dst_image, $params['dstPath'] );
582 imagedestroy( $dst_image );
583 imagedestroy( $src_image );
585 return false; # No error
589 * Escape a string for ImageMagick's property input (e.g. -set -comment)
590 * See InterpretImageProperties() in magick/property.c
592 function escapeMagickProperty( $s ) {
593 // Double the backslashes
594 $s = str_replace( '\\', '\\\\', $s );
595 // Double the percents
596 $s = str_replace( '%', '%%', $s );
597 // Escape initial - or @
598 if ( strlen( $s ) > 0 && ( $s[0] === '-' ||
$s[0] === '@' ) ) {
605 * Escape a string for ImageMagick's input filenames. See ExpandFilenames()
606 * and GetPathComponent() in magick/utility.c.
608 * This won't work with an initial ~ or @, so input files should be prefixed
609 * with the directory name.
611 * Glob character unescaping is broken in ImageMagick before 6.6.1-5, but
612 * it's broken in a way that doesn't involve trying to convert every file
613 * in a directory, so we're better off escaping and waiting for the bugfix
614 * to filter down to users.
616 * @param $path string The file path
617 * @param $scene string The scene specification, or false if there is none
619 function escapeMagickInput( $path, $scene = false ) {
620 # Die on initial metacharacters (caller should prepend path)
621 $firstChar = substr( $path, 0, 1 );
622 if ( $firstChar === '~' ||
$firstChar === '@' ) {
623 throw new MWException( __METHOD__
. ': cannot escape this path name' );
627 $path = preg_replace( '/[*?\[\]{}]/', '\\\\\0', $path );
629 return $this->escapeMagickPath( $path, $scene );
633 * Escape a string for ImageMagick's output filename. See
634 * InterpretImageFilename() in magick/image.c.
636 function escapeMagickOutput( $path, $scene = false ) {
637 $path = str_replace( '%', '%%', $path );
638 return $this->escapeMagickPath( $path, $scene );
642 * Armour a string against ImageMagick's GetPathComponent(). This is a
643 * helper function for escapeMagickInput() and escapeMagickOutput().
645 * @param $path string The file path
646 * @param $scene string The scene specification, or false if there is none
648 protected function escapeMagickPath( $path, $scene = false ) {
649 # Die on format specifiers (other than drive letters). The regex is
650 # meant to match all the formats you get from "convert -list format"
651 if ( preg_match( '/^([a-zA-Z0-9-]+):/', $path, $m ) ) {
652 if ( wfIsWindows() && is_dir( $m[0] ) ) {
653 // OK, it's a drive letter
654 // ImageMagick has a similar exception, see IsMagickConflict()
656 throw new MWException( __METHOD__
. ': unexpected colon character in path name' );
660 # If there are square brackets, add a do-nothing scene specification
661 # to force a literal interpretation
662 if ( $scene === false ) {
663 if ( strpos( $path, '[' ) !== false ) {
673 * Retrieve the version of the installed ImageMagick
674 * You can use PHPs version_compare() to use this value
675 * Value is cached for one hour.
676 * @return String representing the IM version.
678 protected function getMagickVersion() {
681 $cache = $wgMemc->get( "imagemagick-version" );
683 global $wgImageMagickConvertCommand;
684 $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . ' -version';
685 wfDebug( __METHOD__
. ": Running convert -version\n" );
687 $return = wfShellExec( $cmd, $retval );
688 $x = preg_match( '/Version: ImageMagick ([0-9]*\.[0-9]*\.[0-9]*)/', $return, $matches );
690 wfDebug( __METHOD__
. ": ImageMagick version check failed\n" );
693 $wgMemc->set( "imagemagick-version", $matches[1], 3600 );
699 static function imageJpegWrapper( $dst_image, $thumbPath ) {
700 imageinterlace( $dst_image );
701 imagejpeg( $dst_image, $thumbPath, 95 );
705 * On supporting image formats, try to read out the low-level orientation
706 * of the file and return the angle that the file needs to be rotated to
709 * This information is only useful when manipulating the original file;
710 * the width and height we normally work with is logical, and will match
711 * any produced output views.
713 * The base BitmapHandler doesn't understand any metadata formats, so this
714 * is left up to child classes to implement.
717 * @return int 0, 90, 180 or 270
719 public function getRotation( $file ) {
724 * Returns whether the current scaler supports rotation (im and gd do)
728 public static function canRotate() {
729 $scaler = self
::getScalerType( null, false );
732 # ImageMagick supports autorotation
735 # Imagick::rotateImage
738 # GD's imagerotate function is used to rotate images, but not
739 # all precompiled PHP versions have that function
740 return function_exists( 'imagerotate' );
742 # Other scalers don't support rotation
748 * Rerurns whether the file needs to be rendered. Returns true if the
749 * file requires rotation and we are able to rotate it.
754 public function mustRender( $file ) {
755 return self
::canRotate() && $this->getRotation( $file ) != 0;