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 ) {
24 global $wgMaxImageArea;
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() ) {
47 if ( self
::canRotate() ) {
48 $rotation = $this->getRotation( $image );
49 if ( $rotation == 90 ||
$rotation == 270 ) {
50 wfDebug( __METHOD__
. ": Swapping width and height because the file will be rotated $rotation degrees\n" );
52 list( $params['width'], $params['height'] ) =
53 array( $params['height'], $params['width'] );
54 list( $params['physicalWidth'], $params['physicalHeight'] ) =
55 array( $params['physicalHeight'], $params['physicalWidth'] );
60 # Don't thumbnail an image so big that it will fill hard drives and send servers into swap
61 # JPEG has the handy property of allowing thumbnailing without full decompression, so we make
62 # an exception for it.
63 # @todo FIXME: This actually only applies to ImageMagick
64 if ( $mimeType !== 'image/jpeg' &&
65 $srcWidth * $srcHeight > $wgMaxImageArea )
74 * Extracts the width/height if the image will be scaled before rotating
76 * @param $params array Parameters as returned by normaliseParams
77 * @param $rotation int The rotation angle that will be applied
78 * @return array ($width, $height) array
80 public function extractPreRotationDimensions( $params, $rotation ) {
81 if ( $rotation == 90 ||
$rotation == 270 ) {
82 # We'll resize before rotation, so swap the dimensions again
83 $width = $params['physicalHeight'];
84 $height = $params['physicalWidth'];
86 $width = $params['physicalWidth'];
87 $height = $params['physicalHeight'];
89 return array( $width, $height );
93 // Function that returns the number of pixels to be thumbnailed.
94 // Intended for animated GIFs to multiply by the number of frames.
95 function getImageArea( $image, $width, $height ) {
96 return $width * $height;
105 * @return MediaTransformError|ThumbnailImage|TransformParameterError
107 function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
108 if ( !$this->normaliseParams( $image, $params ) ) {
109 return new TransformParameterError( $params );
111 # Create a parameter array to pass to the scaler
112 $scalerParams = array(
113 # The size to which the image will be resized
114 'physicalWidth' => $params['physicalWidth'],
115 'physicalHeight' => $params['physicalHeight'],
116 'physicalDimensions' => "{$params['physicalWidth']}x{$params['physicalHeight']}",
117 # The size of the image on the page
118 'clientWidth' => $params['width'],
119 'clientHeight' => $params['height'],
120 # Comment as will be added to the EXIF of the thumbnail
121 'comment' => isset( $params['descriptionUrl'] ) ?
122 "File source: {$params['descriptionUrl']}" : '',
123 # Properties of the original image
124 'srcWidth' => $image->getWidth(),
125 'srcHeight' => $image->getHeight(),
126 'mimeType' => $image->getMimeType(),
127 'srcPath' => $image->getPath(),
128 'dstPath' => $dstPath,
132 wfDebug( __METHOD__
. ": creating {$scalerParams['physicalDimensions']} thumbnail at $dstPath\n" );
134 if ( !$image->mustRender() &&
135 $scalerParams['physicalWidth'] == $scalerParams['srcWidth']
136 && $scalerParams['physicalHeight'] == $scalerParams['srcHeight'] ) {
138 # normaliseParams (or the user) wants us to return the unscaled image
139 wfDebug( __METHOD__
. ": returning unscaled image\n" );
140 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
143 # Determine scaler type
144 $scaler = self
::getScalerType( $dstPath );
145 wfDebug( __METHOD__
. ": scaler $scaler\n" );
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'], $dstPath );
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 );
167 wfRunHooks( 'BitmapHandlerTransform', array( $this, $image, &$scalerParams, &$mto ) );
168 if ( !is_null( $mto ) ) {
169 wfDebug( __METHOD__
. ": Hook to BitmapHandlerTransform created an mto\n" );
170 $scaler = 'hookaborted';
175 # Handled by the hook above
176 $err = $mto->isError() ?
$mto : false;
179 $err = $this->transformImageMagick( $image, $scalerParams );
182 $err = $this->transformCustom( $image, $scalerParams );
185 $err = $this->transformImageMagickExt( $image, $scalerParams );
189 $err = $this->transformGd( $image, $scalerParams );
193 # Remove the file if a zero-byte thumbnail was created, or if there was an error
194 $removed = $this->removeBadFile( $dstPath, (bool)$err );
196 # transform returned MediaTransforError
198 } elseif ( $removed ) {
199 # Thumbnail was zero-byte and had to be removed
200 return new MediaTransformError( 'thumbnail_error',
201 $scalerParams['clientWidth'], $scalerParams['clientHeight'] );
205 return new ThumbnailImage( $image, $dstUrl, $scalerParams['clientWidth'],
206 $scalerParams['clientHeight'], $dstPath );
211 * Returns which scaler type should be used. Creates parent directories
212 * for $dstPath and returns 'client' on error
214 * @return string client,im,custom,gd
216 protected static function getScalerType( $dstPath, $checkDstPath = true ) {
217 global $wgUseImageResize, $wgUseImageMagick, $wgCustomConvertCommand;
219 if ( !$dstPath && $checkDstPath ) {
220 # No output path available, client side scaling only
222 } elseif ( !$wgUseImageResize ) {
224 } elseif ( $wgUseImageMagick ) {
226 } elseif ( $wgCustomConvertCommand ) {
228 } elseif ( function_exists( 'imagecreatetruecolor' ) ) {
230 } elseif ( class_exists( 'Imagick' ) ) {
236 if ( $scaler != 'client' && $dstPath ) {
237 if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__
) ) {
238 # Unable to create a path for the thumbnail
246 * Get a ThumbnailImage that respresents an image that will be scaled
249 * @param $image File File associated with this thumbnail
250 * @param $params array Array with scaler params
251 * @return ThumbnailImage
253 protected function getClientScalingThumbnailImage( $image, $params ) {
254 return new ThumbnailImage( $image, $image->getURL(),
255 $params['clientWidth'], $params['clientHeight'], $params['srcPath'] );
259 * Transform an image using ImageMagick
261 * @param $image File File associated with this thumbnail
262 * @param $params array Array with scaler params
264 * @return MediaTransformError Error object if error occured, false (=no error) otherwise
266 protected function transformImageMagick( $image, $params ) {
268 global $wgSharpenReductionThreshold, $wgSharpenParameter,
269 $wgMaxAnimatedGifArea,
270 $wgImageMagickTempDir, $wgImageMagickConvertCommand;
276 $animation_post = '';
278 if ( $params['mimeType'] == 'image/jpeg' ) {
279 $quality = "-quality 80"; // 80%
280 # Sharpening, see bug 6193
281 if ( ( $params['physicalWidth'] +
$params['physicalHeight'] )
282 / ( $params['srcWidth'] +
$params['srcHeight'] )
283 < $wgSharpenReductionThreshold ) {
284 $sharpen = "-sharpen " . wfEscapeShellArg( $wgSharpenParameter );
286 // JPEG decoder hint to reduce memory, available since IM 6.5.6-2
287 $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, $params['srcWidth'],
294 $params['srcHeight'] ) > $wgMaxAnimatedGifArea ) {
295 // Extract initial frame only; we're so big it'll
296 // be a total drag. :P
299 } elseif ( $this->isAnimatedImage( $image ) ) {
300 // Coalesce is needed to scale animated GIFs properly (bug 1017).
301 $animation_pre = '-coalesce';
302 // We optimize the output, but -optimize is broken,
303 // use optimizeTransparency instead (bug 11822)
304 if ( version_compare( $this->getMagickVersion(), "6.3.5" ) >= 0 ) {
305 $animation_post = '-fuzz 5% -layers optimizeTransparency';
310 // Use one thread only, to avoid deadlock bugs on OOM
311 $env = array( 'OMP_NUM_THREADS' => 1 );
312 if ( strval( $wgImageMagickTempDir ) !== '' ) {
313 $env['MAGICK_TMPDIR'] = $wgImageMagickTempDir;
316 $rotation = $this->getRotation( $image );
317 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
320 wfEscapeShellArg( $wgImageMagickConvertCommand ) .
321 // Specify white background color, will be used for transparent images
322 // in Internet Explorer/Windows instead of default black.
323 " {$quality} -background white" .
325 wfEscapeShellArg( $this->escapeMagickInput( $params['srcPath'], $scene ) ) .
326 " {$animation_pre}" .
327 // For the -thumbnail option a "!" is needed to force exact size,
328 // or ImageMagick may decide your ratio is wrong and slice off
330 " -thumbnail " . wfEscapeShellArg( "{$width}x{$height}!" ) .
331 // Add the source url as a comment to the thumb, but don't add the flag if there's no comment
332 ( $params['comment'] !== ''
333 ?
" -set comment " . wfEscapeShellArg( $this->escapeMagickProperty( $params['comment'] ) )
335 " -depth 8 $sharpen -auto-orient" .
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, $params['srcWidth'],
382 $params['srcHeight'] ) > $wgMaxAnimatedGifArea ) {
383 // Extract initial frame only; we're so big it'll
384 // be a total drag. :P
385 $im->setImageScene( 0 );
386 } elseif ( $this->isAnimatedImage( $image ) ) {
387 // Coalesce is needed to scale animated GIFs properly (bug 1017).
388 $im = $im->coalesceImages();
392 $rotation = $this->getRotation( $image );
393 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
395 $im->setImageBackgroundColor( new ImagickPixel( 'white' ) );
397 // Call Imagick::thumbnailImage on each frame
398 foreach ( $im as $i => $frame ) {
399 if ( !$frame->thumbnailImage( $width, $height, /* fit */ false ) ) {
400 return $this->getMediaTransformError( $params, "Error scaling frame $i" );
403 $im->setImageDepth( 8 );
406 if ( !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) {
407 return $this->getMediaTransformError( $params, "Error rotating $rotation degrees" );
411 if ( $this->isAnimatedImage( $image ) ) {
412 wfDebug( __METHOD__
. ": Writing animated thumbnail\n" );
413 // This is broken somehow... can't find out how to fix it
414 $result = $im->writeImages( $params['dstPath'], true );
416 $result = $im->writeImage( $params['dstPath'] );
419 return $this->getMediaTransformError( $params,
420 "Unable to write thumbnail to {$params['dstPath']}" );
423 } catch ( ImagickException
$e ) {
424 return $this->getMediaTransformError( $params, $e->getMessage() );
432 * Transform an image using a custom command
434 * @param $image File File associated with this thumbnail
435 * @param $params array Array with scaler params
437 * @return MediaTransformError Error object if error occured, false (=no error) otherwise
439 protected function transformCustom( $image, $params ) {
440 # Use a custom convert command
441 global $wgCustomConvertCommand;
443 # Variables: %s %d %w %h
444 $src = wfEscapeShellArg( $params['srcPath'] );
445 $dst = wfEscapeShellArg( $params['dstPath'] );
446 $cmd = $wgCustomConvertCommand;
447 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
448 $cmd = str_replace( '%h', $params['physicalHeight'],
449 str_replace( '%w', $params['physicalWidth'], $cmd ) ); # Size
450 wfDebug( __METHOD__
. ": Running custom convert command $cmd\n" );
451 wfProfileIn( 'convert' );
453 $err = wfShellExec( $cmd, $retval );
454 wfProfileOut( 'convert' );
456 if ( $retval !== 0 ) {
457 $this->logErrorForExternalProcess( $retval, $err, $cmd );
458 return $this->getMediaTransformError( $params, $err );
460 return false; # No error
464 * Log an error that occured in an external process
470 protected function logErrorForExternalProcess( $retval, $err, $cmd ) {
471 wfDebugLog( 'thumbnail',
472 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
473 wfHostname(), $retval, trim( $err ), $cmd ) );
476 * Get a MediaTransformError with error 'thumbnail_error'
478 * @param $params array Parameter array as passed to the transform* functions
479 * @param $errMsg string Error message
480 * @return MediaTransformError
482 public function getMediaTransformError( $params, $errMsg ) {
483 return new MediaTransformError( 'thumbnail_error', $params['clientWidth'],
484 $params['clientHeight'], $errMsg );
488 * Transform an image using the built in GD library
490 * @param $image File File associated with this thumbnail
491 * @param $params array Array with scaler params
493 * @return MediaTransformError Error object if error occured, false (=no error) otherwise
495 protected function transformGd( $image, $params ) {
496 # Use PHP's builtin GD library functions.
498 # First find out what kind of file this is, and select the correct
499 # input routine for this.
502 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
503 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( __CLASS__
, 'imageJpegWrapper' ) ),
504 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
505 'image/vnd.wap.wbmp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
506 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
508 if ( !isset( $typemap[$params['mimeType']] ) ) {
509 $err = 'Image type not supported';
511 $errMsg = wfMsg ( 'thumbnail_image-type' );
512 return $this->getMediaTransformError( $params, $errMsg );
514 list( $loader, $colorStyle, $saveType ) = $typemap[$params['mimeType']];
516 if ( !function_exists( $loader ) ) {
517 $err = "Incomplete GD library configuration: missing function $loader";
519 $errMsg = wfMsg ( 'thumbnail_gd-library', $loader );
520 return $this->getMediaTransformError( $params, $errMsg );
523 if ( !file_exists( $params['srcPath'] ) ) {
524 $err = "File seems to be missing: {$params['srcPath']}";
526 $errMsg = wfMsg ( 'thumbnail_image-missing', $params['srcPath'] );
527 return $this->getMediaTransformError( $params, $errMsg );
530 $src_image = call_user_func( $loader, $params['srcPath'] );
532 $rotation = function_exists( 'imagerotate' ) ?
$this->getRotation( $image ) : 0;
533 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
534 $dst_image = imagecreatetruecolor( $width, $height );
536 // Initialise the destination image to transparent instead of
537 // the default solid black, to support PNG and GIF transparency nicely
538 $background = imagecolorallocate( $dst_image, 0, 0, 0 );
539 imagecolortransparent( $dst_image, $background );
540 imagealphablending( $dst_image, false );
542 if ( $colorStyle == 'palette' ) {
543 // Don't resample for paletted GIF images.
544 // It may just uglify them, and completely breaks transparency.
545 imagecopyresized( $dst_image, $src_image,
548 imagesx( $src_image ), imagesy( $src_image ) );
550 imagecopyresampled( $dst_image, $src_image,
553 imagesx( $src_image ), imagesy( $src_image ) );
556 if ( $rotation %
360 != 0 && $rotation %
90 == 0 ) {
557 $rot_image = imagerotate( $dst_image, $rotation, 0 );
558 imagedestroy( $dst_image );
559 $dst_image = $rot_image;
562 imagesavealpha( $dst_image, true );
564 call_user_func( $saveType, $dst_image, $params['dstPath'] );
565 imagedestroy( $dst_image );
566 imagedestroy( $src_image );
568 return false; # No error
572 * Escape a string for ImageMagick's property input (e.g. -set -comment)
573 * See InterpretImageProperties() in magick/property.c
575 function escapeMagickProperty( $s ) {
576 // Double the backslashes
577 $s = str_replace( '\\', '\\\\', $s );
578 // Double the percents
579 $s = str_replace( '%', '%%', $s );
580 // Escape initial - or @
581 if ( strlen( $s ) > 0 && ( $s[0] === '-' ||
$s[0] === '@' ) ) {
588 * Escape a string for ImageMagick's input filenames. See ExpandFilenames()
589 * and GetPathComponent() in magick/utility.c.
591 * This won't work with an initial ~ or @, so input files should be prefixed
592 * with the directory name.
594 * Glob character unescaping is broken in ImageMagick before 6.6.1-5, but
595 * it's broken in a way that doesn't involve trying to convert every file
596 * in a directory, so we're better off escaping and waiting for the bugfix
597 * to filter down to users.
599 * @param $path string The file path
600 * @param $scene string The scene specification, or false if there is none
602 function escapeMagickInput( $path, $scene = false ) {
603 # Die on initial metacharacters (caller should prepend path)
604 $firstChar = substr( $path, 0, 1 );
605 if ( $firstChar === '~' ||
$firstChar === '@' ) {
606 throw new MWException( __METHOD__
. ': cannot escape this path name' );
610 $path = preg_replace( '/[*?\[\]{}]/', '\\\\\0', $path );
612 return $this->escapeMagickPath( $path, $scene );
616 * Escape a string for ImageMagick's output filename. See
617 * InterpretImageFilename() in magick/image.c.
619 function escapeMagickOutput( $path, $scene = false ) {
620 $path = str_replace( '%', '%%', $path );
621 return $this->escapeMagickPath( $path, $scene );
625 * Armour a string against ImageMagick's GetPathComponent(). This is a
626 * helper function for escapeMagickInput() and escapeMagickOutput().
628 * @param $path string The file path
629 * @param $scene string The scene specification, or false if there is none
631 protected function escapeMagickPath( $path, $scene = false ) {
632 # Die on format specifiers (other than drive letters). The regex is
633 # meant to match all the formats you get from "convert -list format"
634 if ( preg_match( '/^([a-zA-Z0-9-]+):/', $path, $m ) ) {
635 if ( wfIsWindows() && is_dir( $m[0] ) ) {
636 // OK, it's a drive letter
637 // ImageMagick has a similar exception, see IsMagickConflict()
639 throw new MWException( __METHOD__
. ': unexpected colon character in path name' );
643 # If there are square brackets, add a do-nothing scene specification
644 # to force a literal interpretation
645 if ( $scene === false ) {
646 if ( strpos( $path, '[' ) !== false ) {
656 * Retrieve the version of the installed ImageMagick
657 * You can use PHPs version_compare() to use this value
658 * Value is cached for one hour.
659 * @return String representing the IM version.
661 protected function getMagickVersion() {
664 $cache = $wgMemc->get( "imagemagick-version" );
666 global $wgImageMagickConvertCommand;
667 $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . ' -version';
668 wfDebug( __METHOD__
. ": Running convert -version\n" );
670 $return = wfShellExec( $cmd, $retval );
671 $x = preg_match( '/Version: ImageMagick ([0-9]*\.[0-9]*\.[0-9]*)/', $return, $matches );
673 wfDebug( __METHOD__
. ": ImageMagick version check failed\n" );
676 $wgMemc->set( "imagemagick-version", $matches[1], 3600 );
682 static function imageJpegWrapper( $dst_image, $thumbPath ) {
683 imageinterlace( $dst_image );
684 imagejpeg( $dst_image, $thumbPath, 95 );
688 * Try to read out the orientation of the file and return the angle that
689 * the file needs to be rotated to be viewed
692 * @return int 0, 90, 180 or 270
694 public function getRotation( $file ) {
695 $data = $file->getMetadata();
699 wfSuppressWarnings();
700 $data = unserialize( $data );
702 if ( isset( $data['Orientation'] ) ) {
703 # See http://sylvana.net/jpegcrop/exif_orientation.html
704 switch ( $data['Orientation'] ) {
719 * Returns whether the current scaler supports rotation (im and gd do)
723 public static function canRotate() {
724 $scaler = self
::getScalerType( null, false );
727 # ImageMagick supports autorotation
730 # Imagick::rotateImage
733 # GD's imagerotate function is used to rotate images, but not
734 # all precompiled PHP versions have that function
735 return function_exists( 'imagerotate' );
737 # Other scalers don't support rotation
743 * Rerurns whether the file needs to be rendered. Returns true if the
744 * file requires rotation and we are able to rotate it.
749 public function mustRender( $file ) {
750 return self
::canRotate() && $this->getRotation( $file ) != 0;