3 * Generic handler for bitmap images
10 * Generic handler for bitmap images
14 class BitmapHandler
extends ImageHandler
{
21 function normaliseParams( $image, &$params ) {
22 global $wgMaxImageArea;
23 if ( !parent
::normaliseParams( $image, $params ) ) {
27 $mimeType = $image->getMimeType();
28 $srcWidth = $image->getWidth( $params['page'] );
29 $srcHeight = $image->getHeight( $params['page'] );
31 if ( self
::canRotate() ) {
32 $rotation = $this->getRotation( $image );
33 if ( $rotation == 90 ||
$rotation == 270 ) {
34 wfDebug( __METHOD__
. ": Swapping width and height because the file will be rotated $rotation degrees\n" );
36 $width = $params['width'];
37 $params['width'] = $params['height'];
38 $params['height'] = $width;
42 # Don't make an image bigger than the source
43 $params['physicalWidth'] = $params['width'];
44 $params['physicalHeight'] = $params['height'];
46 if ( $params['physicalWidth'] >= $srcWidth ) {
47 $params['physicalWidth'] = $srcWidth;
48 $params['physicalHeight'] = $srcHeight;
49 # Skip scaling limit checks if no scaling is required
50 if ( !$image->mustRender() )
54 # Don't thumbnail an image so big that it will fill hard drives and send servers into swap
55 # JPEG has the handy property of allowing thumbnailing without full decompression, so we make
56 # an exception for it.
57 # FIXME: This actually only applies to ImageMagick
58 if ( $mimeType !== 'image/jpeg' &&
59 $srcWidth * $srcHeight > $wgMaxImageArea )
68 // Function that returns the number of pixels to be thumbnailed.
69 // Intended for animated GIFs to multiply by the number of frames.
70 function getImageArea( $image, $width, $height ) {
71 return $width * $height;
80 * @return MediaTransformError|ThumbnailImage|TransformParameterError
82 function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
83 if ( !$this->normaliseParams( $image, $params ) ) {
84 return new TransformParameterError( $params );
86 # Create a parameter array to pass to the scaler
87 $scalerParams = array(
88 # The size to which the image will be resized
89 'physicalWidth' => $params['physicalWidth'],
90 'physicalHeight' => $params['physicalHeight'],
91 'physicalDimensions' => "{$params['physicalWidth']}x{$params['physicalHeight']}",
92 # The size of the image on the page
93 'clientWidth' => $params['width'],
94 'clientHeight' => $params['height'],
95 # Comment as will be added to the EXIF of the thumbnail
96 'comment' => isset( $params['descriptionUrl'] ) ?
97 "File source: {$params['descriptionUrl']}" : '',
98 # Properties of the original image
99 'srcWidth' => $image->getWidth(),
100 'srcHeight' => $image->getHeight(),
101 'mimeType' => $image->getMimeType(),
102 'srcPath' => $image->getPath(),
103 'dstPath' => $dstPath,
106 wfDebug( __METHOD__
. ": creating {$scalerParams['physicalDimensions']} thumbnail at $dstPath\n" );
108 if ( !$image->mustRender() &&
109 $scalerParams['physicalWidth'] == $scalerParams['srcWidth']
110 && $scalerParams['physicalHeight'] == $scalerParams['srcHeight'] ) {
112 # normaliseParams (or the user) wants us to return the unscaled image
113 wfDebug( __METHOD__
. ": returning unscaled image\n" );
114 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
117 # Determine scaler type
118 $scaler = self
::getScalerType( $dstPath );
119 wfDebug( __METHOD__
. ": scaler $scaler\n" );
121 if ( $scaler == 'client' ) {
122 # Client-side image scaling, use the source URL
123 # Using the destination URL in a TRANSFORM_LATER request would be incorrect
124 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
127 if ( $flags & self
::TRANSFORM_LATER
) {
128 wfDebug( __METHOD__
. ": Transforming later per flags.\n" );
129 return new ThumbnailImage( $image, $dstUrl, $scalerParams['clientWidth'],
130 $scalerParams['clientHeight'], $dstPath );
133 # Try to make a target path for the thumbnail
134 if ( !wfMkdirParents( dirname( $dstPath ) ) ) {
135 wfDebug( __METHOD__
. ": Unable to create thumbnail destination directory, falling back to client scaling\n" );
136 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
141 $err = $this->transformImageMagick( $image, $scalerParams );
144 $err = $this->transformCustom( $image, $scalerParams );
148 $err = $this->transformGd( $image, $scalerParams );
152 # Remove the file if a zero-byte thumbnail was created, or if there was an error
153 $removed = $this->removeBadFile( $dstPath, (bool)$err );
155 # transform returned MediaTransforError
157 } elseif ( $removed ) {
158 # Thumbnail was zero-byte and had to be removed
159 return new MediaTransformError( 'thumbnail_error',
160 $scalerParams['clientWidth'], $scalerParams['clientHeight'] );
162 return new ThumbnailImage( $image, $dstUrl, $scalerParams['clientWidth'],
163 $scalerParams['clientHeight'], $dstPath );
168 * Returns which scaler type should be used. Creates parent directories
169 * for $dstPath and returns 'client' on error
171 * @return string client,im,custom,gd
173 protected static function getScalerType( $dstPath, $checkDstPath = true ) {
174 global $wgUseImageResize, $wgUseImageMagick, $wgCustomConvertCommand;
176 if ( !$dstPath && $checkDstPath ) {
177 # No output path available, client side scaling only
179 } elseif ( !$wgUseImageResize ) {
181 } elseif ( $wgUseImageMagick ) {
183 } elseif ( $wgCustomConvertCommand ) {
185 } elseif ( function_exists( 'imagecreatetruecolor' ) ) {
191 if ( $scaler != 'client' && $dstPath ) {
192 if ( !wfMkdirParents( dirname( $dstPath ) ) ) {
193 # Unable to create a path for the thumbnail
201 * Get a ThumbnailImage that respresents an image that will be scaled
204 * @param $image File File associated with this thumbnail
205 * @param $params array Array with scaler params
206 * @return ThumbnailImage
208 protected function getClientScalingThumbnailImage( $image, $params ) {
209 return new ThumbnailImage( $image, $image->getURL(),
210 $params['clientWidth'], $params['clientHeight'], $params['srcPath'] );
214 * Transform an image using ImageMagick
216 * @param $image File File associated with this thumbnail
217 * @param $params array Array with scaler params
219 * @return MediaTransformError Error object if error occured, false (=no error) otherwise
221 protected function transformImageMagick( $image, $params ) {
223 global $wgSharpenReductionThreshold, $wgSharpenParameter,
224 $wgMaxAnimatedGifArea,
225 $wgImageMagickTempDir, $wgImageMagickConvertCommand;
231 $animation_post = '';
233 if ( $params['mimeType'] == 'image/jpeg' ) {
234 $quality = "-quality 80"; // 80%
235 # Sharpening, see bug 6193
236 if ( ( $params['physicalWidth'] +
$params['physicalHeight'] )
237 / ( $params['srcWidth'] +
$params['srcHeight'] )
238 < $wgSharpenReductionThreshold ) {
239 $sharpen = "-sharpen " . wfEscapeShellArg( $wgSharpenParameter );
241 // JPEG decoder hint to reduce memory, available since IM 6.5.6-2
242 $decoderHint = "-define jpeg:size={$params['physicalDimensions']}";
244 } elseif ( $params['mimeType'] == 'image/png' ) {
245 $quality = "-quality 95"; // zlib 9, adaptive filtering
247 } elseif ( $params['mimeType'] == 'image/gif' ) {
248 if ( $this->getImageArea( $image, $params['srcWidth'],
249 $params['srcHeight'] ) > $wgMaxAnimatedGifArea ) {
250 // Extract initial frame only; we're so big it'll
251 // be a total drag. :P
254 } elseif ( $this->isAnimatedImage( $image ) ) {
255 // Coalesce is needed to scale animated GIFs properly (bug 1017).
256 $animation_pre = '-coalesce';
257 // We optimize the output, but -optimize is broken,
258 // use optimizeTransparency instead (bug 11822)
259 if ( version_compare( $this->getMagickVersion(), "6.3.5" ) >= 0 ) {
260 $animation_post = '-fuzz 5% -layers optimizeTransparency +map';
265 // Use one thread only, to avoid deadlock bugs on OOM
266 $env = array( 'OMP_NUM_THREADS' => 1 );
267 if ( strval( $wgImageMagickTempDir ) !== '' ) {
268 $env['MAGICK_TMPDIR'] = $wgImageMagickTempDir;
272 wfEscapeShellArg( $wgImageMagickConvertCommand ) .
273 // Specify white background color, will be used for transparent images
274 // in Internet Explorer/Windows instead of default black.
275 " {$quality} -background white" .
277 wfEscapeShellArg( $this->escapeMagickInput( $params['srcPath'], $scene ) ) .
278 " {$animation_pre}" .
279 // For the -thumbnail option a "!" is needed to force exact size,
280 // or ImageMagick may decide your ratio is wrong and slice off
282 " -thumbnail " . wfEscapeShellArg( "{$params['physicalDimensions']}!" ) .
283 // Add the source url as a comment to the thumb, but don't add the flag if there's no comment
284 ( $params['comment'] !== ''
285 ?
" -set comment " . wfEscapeShellArg( $this->escapeMagickProperty( $params['comment'] ) )
287 " -depth 8 $sharpen -auto-orient" .
288 " {$animation_post} " .
289 wfEscapeShellArg( $this->escapeMagickOutput( $params['dstPath'] ) ) . " 2>&1";
291 wfDebug( __METHOD__
. ": running ImageMagick: $cmd\n" );
292 wfProfileIn( 'convert' );
294 $err = wfShellExec( $cmd, $retval, $env );
295 wfProfileOut( 'convert' );
297 if ( $retval !== 0 ) {
298 $this->logErrorForExternalProcess( $retval, $err, $cmd );
299 return $this->getMediaTransformError( $params, $err );
302 return false; # No error
306 * Transform an image using a custom command
308 * @param $image File File associated with this thumbnail
309 * @param $params array Array with scaler params
311 * @return MediaTransformError Error object if error occured, false (=no error) otherwise
313 protected function transformCustom( $image, $params ) {
314 # Use a custom convert command
315 global $wgCustomConvertCommand;
317 # Variables: %s %d %w %h
318 $src = wfEscapeShellArg( $params['srcPath'] );
319 $dst = wfEscapeShellArg( $params['dstPath'] );
320 $cmd = $wgCustomConvertCommand;
321 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
322 $cmd = str_replace( '%h', $params['physicalHeight'],
323 str_replace( '%w', $params['physicalWidth'], $cmd ) ); # Size
324 wfDebug( __METHOD__
. ": Running custom convert command $cmd\n" );
325 wfProfileIn( 'convert' );
327 $err = wfShellExec( $cmd, $retval );
328 wfProfileOut( 'convert' );
330 if ( $retval !== 0 ) {
331 $this->logErrorForExternalProcess( $retval, $err, $cmd );
332 return $this->getMediaTransformError( $params, $err );
334 return false; # No error
338 * Log an error that occured in an external process
344 protected function logErrorForExternalProcess( $retval, $err, $cmd ) {
345 wfDebugLog( 'thumbnail',
346 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
347 wfHostname(), $retval, trim( $err ), $cmd ) );
350 * Get a MediaTransformError with error 'thumbnail_error'
352 * @param $params array Parameter array as passed to the transform* functions
353 * @param $errMsg string Error message
354 * @return MediaTransformError
356 protected function getMediaTransformError( $params, $errMsg ) {
357 return new MediaTransformError( 'thumbnail_error', $params['clientWidth'],
358 $params['clientHeight'], $errMsg );
362 * Transform an image using the built in GD library
364 * @param $image File File associated with this thumbnail
365 * @param $params array Array with scaler params
367 * @return MediaTransformError Error object if error occured, false (=no error) otherwise
369 protected function transformGd( $image, $params ) {
370 # Use PHP's builtin GD library functions.
372 # First find out what kind of file this is, and select the correct
373 # input routine for this.
376 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
377 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( __CLASS__
, 'imageJpegWrapper' ) ),
378 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
379 'image/vnd.wap.wbmp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
380 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
382 if ( !isset( $typemap[$params['mimeType']] ) ) {
383 $err = 'Image type not supported';
385 $errMsg = wfMsg ( 'thumbnail_image-type' );
386 return $this->getMediaTransformError( $params, $errMsg );
388 list( $loader, $colorStyle, $saveType ) = $typemap[$params['mimeType']];
390 if ( !function_exists( $loader ) ) {
391 $err = "Incomplete GD library configuration: missing function $loader";
393 $errMsg = wfMsg ( 'thumbnail_gd-library', $loader );
394 return $this->getMediaTransformError( $params, $errMsg );
397 if ( !file_exists( $params['srcPath'] ) ) {
398 $err = "File seems to be missing: {$params['srcPath']}";
400 $errMsg = wfMsg ( 'thumbnail_image-missing', $params['srcPath'] );
401 return $this->getMediaTransformError( $params, $errMsg );
404 $src_image = call_user_func( $loader, $params['srcPath'] );
406 $rotation = function_exists( 'imagerotate' ) ?
$this->getRotation( $image ) : 0;
407 if ( $rotation == 90 ||
$rotation == 270 ) {
408 # We'll resize before rotation, so swap the dimensions again
409 $width = $params['physicalHeight'];
410 $height = $params['physicalWidth'];
412 $width = $params['physicalWidth'];
413 $height = $params['physicalHeight'];
415 $dst_image = imagecreatetruecolor( $width, $height );
417 // Initialise the destination image to transparent instead of
418 // the default solid black, to support PNG and GIF transparency nicely
419 $background = imagecolorallocate( $dst_image, 0, 0, 0 );
420 imagecolortransparent( $dst_image, $background );
421 imagealphablending( $dst_image, false );
423 if ( $colorStyle == 'palette' ) {
424 // Don't resample for paletted GIF images.
425 // It may just uglify them, and completely breaks transparency.
426 imagecopyresized( $dst_image, $src_image,
429 imagesx( $src_image ), imagesy( $src_image ) );
431 imagecopyresampled( $dst_image, $src_image,
434 imagesx( $src_image ), imagesy( $src_image ) );
437 if ( $rotation %
360 != 0 && $rotation %
90 == 0 ) {
438 $rot_image = imagerotate( $dst_image, $rotation, 0 );
439 imagedestroy( $dst_image );
440 $dst_image = $rot_image;
443 imagesavealpha( $dst_image, true );
445 call_user_func( $saveType, $dst_image, $params['dstPath'] );
446 imagedestroy( $dst_image );
447 imagedestroy( $src_image );
449 return false; # No error
453 * Escape a string for ImageMagick's property input (e.g. -set -comment)
454 * See InterpretImageProperties() in magick/property.c
456 function escapeMagickProperty( $s ) {
457 // Double the backslashes
458 $s = str_replace( '\\', '\\\\', $s );
459 // Double the percents
460 $s = str_replace( '%', '%%', $s );
461 // Escape initial - or @
462 if ( strlen( $s ) > 0 && ( $s[0] === '-' ||
$s[0] === '@' ) ) {
469 * Escape a string for ImageMagick's input filenames. See ExpandFilenames()
470 * and GetPathComponent() in magick/utility.c.
472 * This won't work with an initial ~ or @, so input files should be prefixed
473 * with the directory name.
475 * Glob character unescaping is broken in ImageMagick before 6.6.1-5, but
476 * it's broken in a way that doesn't involve trying to convert every file
477 * in a directory, so we're better off escaping and waiting for the bugfix
478 * to filter down to users.
480 * @param $path string The file path
481 * @param $scene string The scene specification, or false if there is none
483 function escapeMagickInput( $path, $scene = false ) {
484 # Die on initial metacharacters (caller should prepend path)
485 $firstChar = substr( $path, 0, 1 );
486 if ( $firstChar === '~' ||
$firstChar === '@' ) {
487 throw new MWException( __METHOD__
. ': cannot escape this path name' );
491 $path = preg_replace( '/[*?\[\]{}]/', '\\\\\0', $path );
493 return $this->escapeMagickPath( $path, $scene );
497 * Escape a string for ImageMagick's output filename. See
498 * InterpretImageFilename() in magick/image.c.
500 function escapeMagickOutput( $path, $scene = false ) {
501 $path = str_replace( '%', '%%', $path );
502 return $this->escapeMagickPath( $path, $scene );
506 * Armour a string against ImageMagick's GetPathComponent(). This is a
507 * helper function for escapeMagickInput() and escapeMagickOutput().
509 * @param $path string The file path
510 * @param $scene string The scene specification, or false if there is none
512 protected function escapeMagickPath( $path, $scene = false ) {
513 # Die on format specifiers (other than drive letters). The regex is
514 # meant to match all the formats you get from "convert -list format"
515 if ( preg_match( '/^([a-zA-Z0-9-]+):/', $path, $m ) ) {
516 if ( wfIsWindows() && is_dir( $m[0] ) ) {
517 // OK, it's a drive letter
518 // ImageMagick has a similar exception, see IsMagickConflict()
520 throw new MWException( __METHOD__
. ': unexpected colon character in path name' );
524 # If there are square brackets, add a do-nothing scene specification
525 # to force a literal interpretation
526 if ( $scene === false ) {
527 if ( strpos( $path, '[' ) !== false ) {
537 * Retrieve the version of the installed ImageMagick
538 * You can use PHPs version_compare() to use this value
539 * Value is cached for one hour.
540 * @return String representing the IM version.
542 protected function getMagickVersion() {
545 $cache = $wgMemc->get( "imagemagick-version" );
547 global $wgImageMagickConvertCommand;
548 $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . ' -version';
549 wfDebug( __METHOD__
. ": Running convert -version\n" );
551 $return = wfShellExec( $cmd, $retval );
552 $x = preg_match( '/Version: ImageMagick ([0-9]*\.[0-9]*\.[0-9]*)/', $return, $matches );
554 wfDebug( __METHOD__
. ": ImageMagick version check failed\n" );
557 $wgMemc->set( "imagemagick-version", $matches[1], 3600 );
563 static function imageJpegWrapper( $dst_image, $thumbPath ) {
564 imageinterlace( $dst_image );
565 imagejpeg( $dst_image, $thumbPath, 95 );
569 function getMetadata( $image, $filename ) {
571 if ( $wgShowEXIF && file_exists( $filename ) ) {
572 $exif = new Exif( $filename );
573 $data = $exif->getFilteredData();
575 $data['MEDIAWIKI_EXIF_VERSION'] = Exif
::version();
576 return serialize( $data );
585 function getMetadataType( $image ) {
589 function isMetadataValid( $image, $metadata ) {
591 if ( !$wgShowEXIF ) {
592 # Metadata disabled and so an empty field is expected
595 if ( $metadata === '0' ) {
596 # Special value indicating that there is no EXIF data in the file
599 wfSuppressWarnings();
600 $exif = unserialize( $metadata );
602 if ( !isset( $exif['MEDIAWIKI_EXIF_VERSION'] ) ||
603 $exif['MEDIAWIKI_EXIF_VERSION'] != Exif
::version() )
606 wfDebug( __METHOD__
. ": wrong version\n" );
613 * Get a list of EXIF metadata items which should be displayed when
614 * the metadata table is collapsed.
616 * @return array of strings
619 function visibleMetadataFields() {
621 $lines = explode( "\n", wfMsgForContent( 'metadata-fields' ) );
622 foreach ( $lines as $line ) {
624 if ( preg_match( '/^\\*\s*(.*?)\s*$/', $line, $matches ) ) {
625 $fields[] = $matches[1];
628 $fields = array_map( 'strtolower', $fields );
636 function formatMetadata( $image ) {
638 'visible' => array(),
639 'collapsed' => array()
641 $metadata = $image->getMetadata();
645 $exif = unserialize( $metadata );
649 unset( $exif['MEDIAWIKI_EXIF_VERSION'] );
650 $format = new FormatExif( $exif );
652 $formatted = $format->getFormattedData();
653 // Sort fields into visible and collapsed
654 $visibleFields = $this->visibleMetadataFields();
655 foreach ( $formatted as $name => $value ) {
656 $tag = strtolower( $name );
657 self
::addMeta( $result,
658 in_array( $tag, $visibleFields ) ?
'visible' : 'collapsed',
668 * Try to read out the orientation of the file and return the angle that
669 * the file needs to be rotated to be viewed
672 * @return int 0, 90, 180 or 270
674 public function getRotation( $file ) {
675 $data = $file->getMetadata();
679 $data = unserialize( $data );
680 if ( isset( $data['Orientation'] ) ) {
681 # See http://sylvana.net/jpegcrop/exif_orientation.html
682 switch ( $data['Orientation'] ) {
696 * Returns whether the current scaler supports rotation (im and gd do)
700 public static function canRotate() {
701 $scaler = self
::getScalerType( null, false );
704 # ImageMagick supports autorotation
707 # GD's imagerotate function is used to rotate images, but not
708 # all precompiled PHP versions have that function
709 return function_exists( 'imagerotate' );
711 # Other scalers don't support rotation
717 * Rerurns whether the file needs to be rendered. Returns true if the
718 * file requires rotation and we are able to rotate it.
723 public function mustRender( $file ) {
724 return self
::canRotate() && $this->getRotation( $file ) != 0;