fa9067d8c9a224609fc05b006c7ae377da930742
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';
307 // Use one thread only, to avoid deadlock bugs on OOM
308 $env = array( 'OMP_NUM_THREADS' => 1 );
309 if ( strval( $wgImageMagickTempDir ) !== '' ) {
310 $env['MAGICK_TMPDIR'] = $wgImageMagickTempDir;
313 $rotation = $this->getRotation( $image );
314 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
317 wfEscapeShellArg( $wgImageMagickConvertCommand ) .
318 // Specify white background color, will be used for transparent images
319 // in Internet Explorer/Windows instead of default black.
320 " {$quality} -background white" .
322 wfEscapeShellArg( $this->escapeMagickInput( $params['srcPath'], $scene ) ) .
323 " {$animation_pre}" .
324 // For the -thumbnail option a "!" is needed to force exact size,
325 // or ImageMagick may decide your ratio is wrong and slice off
327 " -thumbnail " . wfEscapeShellArg( "{$width}x{$height}!" ) .
328 // Add the source url as a comment to the thumb, but don't add the flag if there's no comment
329 ( $params['comment'] !== ''
330 ?
" -set comment " . wfEscapeShellArg( $this->escapeMagickProperty( $params['comment'] ) )
332 " -depth 8 $sharpen " .
333 " -rotate -$rotation " .
334 " {$animation_post} " .
335 wfEscapeShellArg( $this->escapeMagickOutput( $params['dstPath'] ) ) . " 2>&1";
337 wfDebug( __METHOD__
. ": running ImageMagick: $cmd\n" );
338 wfProfileIn( 'convert' );
340 $err = wfShellExec( $cmd, $retval, $env );
341 wfProfileOut( 'convert' );
343 if ( $retval !== 0 ) {
344 $this->logErrorForExternalProcess( $retval, $err, $cmd );
345 return $this->getMediaTransformError( $params, $err );
348 return false; # No error
352 * Transform an image using the Imagick PHP extension
354 * @param $image File File associated with this thumbnail
355 * @param $params array Array with scaler params
357 * @return MediaTransformError Error object if error occured, false (=no error) otherwise
359 protected function transformImageMagickExt( $image, $params ) {
360 global $wgSharpenReductionThreshold, $wgSharpenParameter, $wgMaxAnimatedGifArea;
364 $im->readImage( $params['srcPath'] );
366 if ( $params['mimeType'] == 'image/jpeg' ) {
367 // Sharpening, see bug 6193
368 if ( ( $params['physicalWidth'] +
$params['physicalHeight'] )
369 / ( $params['srcWidth'] +
$params['srcHeight'] )
370 < $wgSharpenReductionThreshold ) {
371 // Hack, since $wgSharpenParamater is written specifically for the command line convert
372 list( $radius, $sigma ) = explode( 'x', $wgSharpenParameter );
373 $im->sharpenImage( $radius, $sigma );
375 $im->setCompressionQuality( 80 );
376 } elseif( $params['mimeType'] == 'image/png' ) {
377 $im->setCompressionQuality( 95 );
378 } elseif ( $params['mimeType'] == 'image/gif' ) {
379 if ( $this->getImageArea( $image ) > $wgMaxAnimatedGifArea ) {
380 // Extract initial frame only; we're so big it'll
381 // be a total drag. :P
382 $im->setImageScene( 0 );
383 } elseif ( $this->isAnimatedImage( $image ) ) {
384 // Coalesce is needed to scale animated GIFs properly (bug 1017).
385 $im = $im->coalesceImages();
389 $rotation = $this->getRotation( $image );
390 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
392 $im->setImageBackgroundColor( new ImagickPixel( 'white' ) );
394 // Call Imagick::thumbnailImage on each frame
395 foreach ( $im as $i => $frame ) {
396 if ( !$frame->thumbnailImage( $width, $height, /* fit */ false ) ) {
397 return $this->getMediaTransformError( $params, "Error scaling frame $i" );
400 $im->setImageDepth( 8 );
403 if ( !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) {
404 return $this->getMediaTransformError( $params, "Error rotating $rotation degrees" );
408 if ( $this->isAnimatedImage( $image ) ) {
409 wfDebug( __METHOD__
. ": Writing animated thumbnail\n" );
410 // This is broken somehow... can't find out how to fix it
411 $result = $im->writeImages( $params['dstPath'], true );
413 $result = $im->writeImage( $params['dstPath'] );
416 return $this->getMediaTransformError( $params,
417 "Unable to write thumbnail to {$params['dstPath']}" );
420 } catch ( ImagickException
$e ) {
421 return $this->getMediaTransformError( $params, $e->getMessage() );
429 * Transform an image using a custom command
431 * @param $image File File associated with this thumbnail
432 * @param $params array Array with scaler params
434 * @return MediaTransformError Error object if error occured, false (=no error) otherwise
436 protected function transformCustom( $image, $params ) {
437 # Use a custom convert command
438 global $wgCustomConvertCommand;
440 # Variables: %s %d %w %h
441 $src = wfEscapeShellArg( $params['srcPath'] );
442 $dst = wfEscapeShellArg( $params['dstPath'] );
443 $cmd = $wgCustomConvertCommand;
444 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
445 $cmd = str_replace( '%h', $params['physicalHeight'],
446 str_replace( '%w', $params['physicalWidth'], $cmd ) ); # Size
447 wfDebug( __METHOD__
. ": Running custom convert command $cmd\n" );
448 wfProfileIn( 'convert' );
450 $err = wfShellExec( $cmd, $retval );
451 wfProfileOut( 'convert' );
453 if ( $retval !== 0 ) {
454 $this->logErrorForExternalProcess( $retval, $err, $cmd );
455 return $this->getMediaTransformError( $params, $err );
457 return false; # No error
461 * Log an error that occured in an external process
467 protected function logErrorForExternalProcess( $retval, $err, $cmd ) {
468 wfDebugLog( 'thumbnail',
469 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
470 wfHostname(), $retval, trim( $err ), $cmd ) );
473 * Get a MediaTransformError with error 'thumbnail_error'
475 * @param $params array Parameter array as passed to the transform* functions
476 * @param $errMsg string Error message
477 * @return MediaTransformError
479 public function getMediaTransformError( $params, $errMsg ) {
480 return new MediaTransformError( 'thumbnail_error', $params['clientWidth'],
481 $params['clientHeight'], $errMsg );
485 * Transform an image using the built in GD library
487 * @param $image File File associated with this thumbnail
488 * @param $params array Array with scaler params
490 * @return MediaTransformError Error object if error occured, false (=no error) otherwise
492 protected function transformGd( $image, $params ) {
493 # Use PHP's builtin GD library functions.
495 # First find out what kind of file this is, and select the correct
496 # input routine for this.
499 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
500 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( __CLASS__
, 'imageJpegWrapper' ) ),
501 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
502 'image/vnd.wap.wbmp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
503 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
505 if ( !isset( $typemap[$params['mimeType']] ) ) {
506 $err = 'Image type not supported';
508 $errMsg = wfMsg ( 'thumbnail_image-type' );
509 return $this->getMediaTransformError( $params, $errMsg );
511 list( $loader, $colorStyle, $saveType ) = $typemap[$params['mimeType']];
513 if ( !function_exists( $loader ) ) {
514 $err = "Incomplete GD library configuration: missing function $loader";
516 $errMsg = wfMsg ( 'thumbnail_gd-library', $loader );
517 return $this->getMediaTransformError( $params, $errMsg );
520 if ( !file_exists( $params['srcPath'] ) ) {
521 $err = "File seems to be missing: {$params['srcPath']}";
523 $errMsg = wfMsg ( 'thumbnail_image-missing', $params['srcPath'] );
524 return $this->getMediaTransformError( $params, $errMsg );
527 $src_image = call_user_func( $loader, $params['srcPath'] );
529 $rotation = function_exists( 'imagerotate' ) ?
$this->getRotation( $image ) : 0;
530 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
531 $dst_image = imagecreatetruecolor( $width, $height );
533 // Initialise the destination image to transparent instead of
534 // the default solid black, to support PNG and GIF transparency nicely
535 $background = imagecolorallocate( $dst_image, 0, 0, 0 );
536 imagecolortransparent( $dst_image, $background );
537 imagealphablending( $dst_image, false );
539 if ( $colorStyle == 'palette' ) {
540 // Don't resample for paletted GIF images.
541 // It may just uglify them, and completely breaks transparency.
542 imagecopyresized( $dst_image, $src_image,
545 imagesx( $src_image ), imagesy( $src_image ) );
547 imagecopyresampled( $dst_image, $src_image,
550 imagesx( $src_image ), imagesy( $src_image ) );
553 if ( $rotation %
360 != 0 && $rotation %
90 == 0 ) {
554 $rot_image = imagerotate( $dst_image, $rotation, 0 );
555 imagedestroy( $dst_image );
556 $dst_image = $rot_image;
559 imagesavealpha( $dst_image, true );
561 call_user_func( $saveType, $dst_image, $params['dstPath'] );
562 imagedestroy( $dst_image );
563 imagedestroy( $src_image );
565 return false; # No error
569 * Escape a string for ImageMagick's property input (e.g. -set -comment)
570 * See InterpretImageProperties() in magick/property.c
572 function escapeMagickProperty( $s ) {
573 // Double the backslashes
574 $s = str_replace( '\\', '\\\\', $s );
575 // Double the percents
576 $s = str_replace( '%', '%%', $s );
577 // Escape initial - or @
578 if ( strlen( $s ) > 0 && ( $s[0] === '-' ||
$s[0] === '@' ) ) {
585 * Escape a string for ImageMagick's input filenames. See ExpandFilenames()
586 * and GetPathComponent() in magick/utility.c.
588 * This won't work with an initial ~ or @, so input files should be prefixed
589 * with the directory name.
591 * Glob character unescaping is broken in ImageMagick before 6.6.1-5, but
592 * it's broken in a way that doesn't involve trying to convert every file
593 * in a directory, so we're better off escaping and waiting for the bugfix
594 * to filter down to users.
596 * @param $path string The file path
597 * @param $scene string The scene specification, or false if there is none
599 function escapeMagickInput( $path, $scene = false ) {
600 # Die on initial metacharacters (caller should prepend path)
601 $firstChar = substr( $path, 0, 1 );
602 if ( $firstChar === '~' ||
$firstChar === '@' ) {
603 throw new MWException( __METHOD__
. ': cannot escape this path name' );
607 $path = preg_replace( '/[*?\[\]{}]/', '\\\\\0', $path );
609 return $this->escapeMagickPath( $path, $scene );
613 * Escape a string for ImageMagick's output filename. See
614 * InterpretImageFilename() in magick/image.c.
616 function escapeMagickOutput( $path, $scene = false ) {
617 $path = str_replace( '%', '%%', $path );
618 return $this->escapeMagickPath( $path, $scene );
622 * Armour a string against ImageMagick's GetPathComponent(). This is a
623 * helper function for escapeMagickInput() and escapeMagickOutput().
625 * @param $path string The file path
626 * @param $scene string The scene specification, or false if there is none
628 protected function escapeMagickPath( $path, $scene = false ) {
629 # Die on format specifiers (other than drive letters). The regex is
630 # meant to match all the formats you get from "convert -list format"
631 if ( preg_match( '/^([a-zA-Z0-9-]+):/', $path, $m ) ) {
632 if ( wfIsWindows() && is_dir( $m[0] ) ) {
633 // OK, it's a drive letter
634 // ImageMagick has a similar exception, see IsMagickConflict()
636 throw new MWException( __METHOD__
. ': unexpected colon character in path name' );
640 # If there are square brackets, add a do-nothing scene specification
641 # to force a literal interpretation
642 if ( $scene === false ) {
643 if ( strpos( $path, '[' ) !== false ) {
653 * Retrieve the version of the installed ImageMagick
654 * You can use PHPs version_compare() to use this value
655 * Value is cached for one hour.
656 * @return String representing the IM version.
658 protected function getMagickVersion() {
661 $cache = $wgMemc->get( "imagemagick-version" );
663 global $wgImageMagickConvertCommand;
664 $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . ' -version';
665 wfDebug( __METHOD__
. ": Running convert -version\n" );
667 $return = wfShellExec( $cmd, $retval );
668 $x = preg_match( '/Version: ImageMagick ([0-9]*\.[0-9]*\.[0-9]*)/', $return, $matches );
670 wfDebug( __METHOD__
. ": ImageMagick version check failed\n" );
673 $wgMemc->set( "imagemagick-version", $matches[1], 3600 );
679 static function imageJpegWrapper( $dst_image, $thumbPath ) {
680 imageinterlace( $dst_image );
681 imagejpeg( $dst_image, $thumbPath, 95 );
685 * On supporting image formats, try to read out the low-level orientation
686 * of the file and return the angle that the file needs to be rotated to
689 * This information is only useful when manipulating the original file;
690 * the width and height we normally work with is logical, and will match
691 * any produced output views.
693 * The base BitmapHandler doesn't understand any metadata formats, so this
694 * is left up to child classes to implement.
697 * @return int 0, 90, 180 or 270
699 public function getRotation( $file ) {
704 * Returns whether the current scaler supports rotation (im and gd do)
708 public static function canRotate() {
709 $scaler = self
::getScalerType( null, false );
712 # ImageMagick supports autorotation
715 # Imagick::rotateImage
718 # GD's imagerotate function is used to rotate images, but not
719 # all precompiled PHP versions have that function
720 return function_exists( 'imagerotate' );
722 # Other scalers don't support rotation
728 * Rerurns whether the file needs to be rendered. Returns true if the
729 * file requires rotation and we are able to rotate it.
734 public function mustRender( $file ) {
735 return self
::canRotate() && $this->getRotation( $file ) != 0;