3 * Generic handler for bitmap images
10 * Generic handler for bitmap images
14 class BitmapHandler
extends ImageHandler
{
15 function normaliseParams( $image, &$params ) {
16 global $wgMaxImageArea;
17 if ( !parent
::normaliseParams( $image, $params ) ) {
21 $mimeType = $image->getMimeType();
22 $srcWidth = $image->getWidth( $params['page'] );
23 $srcHeight = $image->getHeight( $params['page'] );
25 if ( $this->canRotate() ) {
26 $rotation = $this->getRotation( $image );
27 if ( $rotation == 90 ||
$rotation == 270 ) {
28 wfDebug( __METHOD__
. ": Swapping width and height because the file will be rotation $rotation degrees\n" );
30 $width = $params['width'];
31 $params['width'] = $params['height'];
32 $params['height'] = $width;
36 # Don't make an image bigger than the source
37 $params['physicalWidth'] = $params['width'];
38 $params['physicalHeight'] = $params['height'];
40 if ( $params['physicalWidth'] >= $srcWidth ) {
41 $params['physicalWidth'] = $srcWidth;
42 $params['physicalHeight'] = $srcHeight;
43 # Skip scaling limit checks if no scaling is required
44 if ( !$image->mustRender() )
48 # Don't thumbnail an image so big that it will fill hard drives and send servers into swap
49 # JPEG has the handy property of allowing thumbnailing without full decompression, so we make
50 # an exception for it.
51 # FIXME: This actually only applies to ImageMagick
52 if ( $mimeType !== 'image/jpeg' &&
53 $srcWidth * $srcHeight > $wgMaxImageArea )
62 // Function that returns the number of pixels to be thumbnailed.
63 // Intended for animated GIFs to multiply by the number of frames.
64 function getImageArea( $image, $width, $height ) {
65 return $width * $height;
68 function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
69 if ( !$this->normaliseParams( $image, $params ) ) {
70 return new TransformParameterError( $params );
72 # Create a parameter array to pass to the scaler
73 $scalerParams = array(
74 # The size to which the image will be resized
75 'physicalWidth' => $params['physicalWidth'],
76 'physicalHeight' => $params['physicalHeight'],
77 'physicalDimensions' => "{$params['physicalWidth']}x{$params['physicalHeight']}",
78 # The size of the image on the page
79 'clientWidth' => $params['width'],
80 'clientHeight' => $params['height'],
81 # Comment as will be added to the EXIF of the thumbnail
82 'comment' => isset( $params['descriptionUrl'] ) ?
83 "File source: {$params['descriptionUrl']}" : '',
84 # Properties of the original image
85 'srcWidth' => $image->getWidth(),
86 'srcHeight' => $image->getHeight(),
87 'mimeType' => $image->getMimeType(),
88 'srcPath' => $image->getPath(),
89 'dstPath' => $dstPath,
92 wfDebug( __METHOD__
. ": creating {$scalerParams['physicalDimensions']} thumbnail at $dstPath\n" );
94 if ( !$image->mustRender() &&
95 $scalerParams['physicalWidth'] == $scalerParams['srcWidth']
96 && $scalerParams['physicalHeight'] == $scalerParams['srcHeight'] ) {
98 # normaliseParams (or the user) wants us to return the unscaled image
99 wfDebug( __METHOD__
. ": returning unscaled image\n" );
100 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
103 # Determine scaler type
104 $scaler = $this->getScalerType( $dstPath );
105 wfDebug( __METHOD__
. ": scaler $scaler\n" );
107 if ( $scaler == 'client' ) {
108 # Client-side image scaling, use the source URL
109 # Using the destination URL in a TRANSFORM_LATER request would be incorrect
110 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
113 if ( $flags & self
::TRANSFORM_LATER
) {
114 wfDebug( __METHOD__
. ": Transforming later per flags.\n" );
115 return new ThumbnailImage( $image, $dstUrl, $scalerParams['clientWidth'],
116 $scalerParams['clientHeight'], $dstPath );
119 # Try to make a target path for the thumbnail
120 if ( !wfMkdirParents( dirname( $dstPath ) ) ) {
121 wfDebug( __METHOD__
. ": Unable to create thumbnail destination directory, falling back to client scaling\n" );
122 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
127 $err = $this->transformImageMagick( $image, $scalerParams );
130 $err = $this->transformCustom( $image, $scalerParams );
134 $err = $this->transformGd( $image, $scalerParams );
138 # Remove the file if a zero-byte thumbnail was created, or if there was an error
139 $removed = $this->removeBadFile( $dstPath, (bool)$err );
141 # transform returned MediaTransforError
143 } elseif ( $removed ) {
144 # Thumbnail was zero-byte and had to be removed
145 return new MediaTransformError( 'thumbnail_error',
146 $scalerParams['clientWidth'], $scalerParams['clientHeight'] );
148 return new ThumbnailImage( $image, $dstUrl, $scalerParams['clientWidth'],
149 $scalerParams['clientHeight'], $dstPath );
154 * Returns which scaler type should be used. Creates parent directories
155 * for $dstPath and returns 'client' on error
157 * @return string client,im,custom,gd
159 protected function getScalerType( $dstPath, $checkDstPath = true ) {
160 global $wgUseImageResize, $wgUseImageMagick, $wgCustomConvertCommand;
162 if ( !$dstPath && $checkDstPath ) {
163 # No output path available, client side scaling only
165 } elseif ( !$wgUseImageResize ) {
167 } elseif ( $wgUseImageMagick ) {
169 } elseif ( $wgCustomConvertCommand ) {
171 } elseif ( function_exists( 'imagecreatetruecolor' ) ) {
177 if ( $scaler != 'client' && $dstPath ) {
178 if ( !wfMkdirParents( dirname( $dstPath ) ) ) {
179 # Unable to create a path for the thumbnail
187 * Get a ThumbnailImage that respresents an image that will be scaled
190 * @param $image File File associated with this thumbnail
191 * @param $params array Array with scaler params
192 * @return ThumbnailImage
194 protected function getClientScalingThumbnailImage( $image, $params ) {
195 return new ThumbnailImage( $image, $image->getURL(),
196 $params['clientWidth'], $params['clientHeight'], $params['srcPath'] );
200 * Transform an image using ImageMagick
202 * @param $image File File associated with this thumbnail
203 * @param $params array Array with scaler params
205 * @return MediaTransformError Error object if error occured, false (=no error) otherwise
207 protected function transformImageMagick( $image, $params ) {
209 global $wgSharpenReductionThreshold, $wgSharpenParameter,
210 $wgMaxAnimatedGifArea,
211 $wgImageMagickTempDir, $wgImageMagickConvertCommand;
217 $animation_post = '';
219 if ( $params['mimeType'] == 'image/jpeg' ) {
220 $quality = "-quality 80"; // 80%
221 # Sharpening, see bug 6193
222 if ( ( $params['physicalWidth'] +
$params['physicalHeight'] )
223 / ( $params['srcWidth'] +
$params['srcHeight'] )
224 < $wgSharpenReductionThreshold ) {
225 $sharpen = "-sharpen " . wfEscapeShellArg( $wgSharpenParameter );
227 // JPEG decoder hint to reduce memory, available since IM 6.5.6-2
228 $decoderHint = "-define jpeg:size={$params['physicalDimensions']}";
230 } elseif ( $params['mimeType'] == 'image/png' ) {
231 $quality = "-quality 95"; // zlib 9, adaptive filtering
233 } elseif ( $params['mimeType'] == 'image/gif' ) {
234 if ( $this->getImageArea( $image, $params['srcWidth'],
235 $params['srcHeight'] ) > $wgMaxAnimatedGifArea ) {
236 // Extract initial frame only; we're so big it'll
237 // be a total drag. :P
240 } elseif ( $this->isAnimatedImage( $image ) ) {
241 // Coalesce is needed to scale animated GIFs properly (bug 1017).
242 $animation_pre = '-coalesce';
243 // We optimize the output, but -optimize is broken,
244 // use optimizeTransparency instead (bug 11822)
245 if ( version_compare( $this->getMagickVersion(), "6.3.5" ) >= 0 ) {
246 $animation_post = '-fuzz 5% -layers optimizeTransparency +map';
251 // Use one thread only, to avoid deadlock bugs on OOM
252 $env = array( 'OMP_NUM_THREADS' => 1 );
253 if ( strval( $wgImageMagickTempDir ) !== '' ) {
254 $env['MAGICK_TMPDIR'] = $wgImageMagickTempDir;
258 wfEscapeShellArg( $wgImageMagickConvertCommand ) .
259 // Specify white background color, will be used for transparent images
260 // in Internet Explorer/Windows instead of default black.
261 " {$quality} -background white" .
263 wfEscapeShellArg( $this->escapeMagickInput( $params['srcPath'], $scene ) ) .
264 " {$animation_pre}" .
265 // For the -thumbnail option a "!" is needed to force exact size,
266 // or ImageMagick may decide your ratio is wrong and slice off
268 " -thumbnail " . wfEscapeShellArg( "{$params['physicalDimensions']}!" ) .
269 // Add the source url as a comment to the thumb, but don't add the flag if there's no comment
270 ( $params['comment'] !== ''
271 ?
" -set comment " . wfEscapeShellArg( $this->escapeMagickProperty( $params['comment'] ) )
273 " -depth 8 $sharpen -auto-orient" .
274 " {$animation_post} " .
275 wfEscapeShellArg( $this->escapeMagickOutput( $params['dstPath'] ) ) . " 2>&1";
277 wfDebug( __METHOD__
. ": running ImageMagick: $cmd\n" );
278 wfProfileIn( 'convert' );
280 $err = wfShellExec( $cmd, $retval, $env );
281 wfProfileOut( 'convert' );
283 if ( $retval !== 0 ) {
284 $this->logErrorForExternalProcess( $retval, $err, $cmd );
285 return $this->getMediaTransformError( $params, $err );
288 return false; # No error
292 * Transform an image using a custom command
294 * @param $image File File associated with this thumbnail
295 * @param $params array Array with scaler params
297 * @return MediaTransformError Error object if error occured, false (=no error) otherwise
299 protected function transformCustom( $image, $params ) {
300 # Use a custom convert command
301 global $wgCustomConvertCommand;
303 # Variables: %s %d %w %h
304 $src = wfEscapeShellArg( $params['srcPath'] );
305 $dst = wfEscapeShellArg( $params['dstPath'] );
306 $cmd = $wgCustomConvertCommand;
307 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
308 $cmd = str_replace( '%h', $params['physicalHeight'],
309 str_replace( '%w', $params['physicalWidth'], $cmd ) ); # Size
310 wfDebug( __METHOD__
. ": Running custom convert command $cmd\n" );
311 wfProfileIn( 'convert' );
313 $err = wfShellExec( $cmd, $retval );
314 wfProfileOut( 'convert' );
316 if ( $retval !== 0 ) {
317 $this->logErrorForExternalProcess( $retval, $err, $cmd );
318 return $this->getMediaTransformError( $params, $err );
320 return false; # No error
324 * Log an error that occured in an external process
330 protected function logErrorForExternalProcess( $retval, $err, $cmd ) {
331 wfDebugLog( 'thumbnail',
332 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
333 wfHostname(), $retval, trim( $err ), $cmd ) );
336 * Get a MediaTransformError with error 'thumbnail_error'
338 * @param $params array Parameter array as passed to the transform* functions
339 * @param $errMsg string Error message
340 * @return MediaTransformError
342 protected function getMediaTransformError( $params, $errMsg ) {
343 return new MediaTransformError( 'thumbnail_error', $params['clientWidth'],
344 $params['clientHeight'], $errMsg );
348 * Transform an image using the built in GD library
350 * @param $image File File associated with this thumbnail
351 * @param $params array Array with scaler params
353 * @return MediaTransformError Error object if error occured, false (=no error) otherwise
355 protected function transformGd( $image, $params ) {
356 # Use PHP's builtin GD library functions.
358 # First find out what kind of file this is, and select the correct
359 # input routine for this.
362 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
363 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( __CLASS__
, 'imageJpegWrapper' ) ),
364 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
365 'image/vnd.wap.wbmp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
366 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
368 if ( !isset( $typemap[$params['mimeType']] ) ) {
369 $err = 'Image type not supported';
371 $errMsg = wfMsg ( 'thumbnail_image-type' );
372 return $this->getMediaTransformError( $params, $errMsg );
374 list( $loader, $colorStyle, $saveType ) = $typemap[$params['mimeType']];
376 if ( !function_exists( $loader ) ) {
377 $err = "Incomplete GD library configuration: missing function $loader";
379 $errMsg = wfMsg ( 'thumbnail_gd-library', $loader );
380 return $this->getMediaTransformError( $params, $errMsg );
383 if ( !file_exists( $params['srcPath'] ) ) {
384 $err = "File seems to be missing: {$params['srcPath']}";
386 $errMsg = wfMsg ( 'thumbnail_image-missing', $params['srcPath'] );
387 return $this->getMediaTransformError( $params, $errMsg );
390 $src_image = call_user_func( $loader, $params['srcPath'] );
391 $rotation = $this->getRotation( $image );
392 if ( $rotation == 90 ||
$rotation == 270 ) {
393 # We'll resize before rotation, so swap the dimensions again
394 $width = $params['physicalHeight'];
395 $height = $params['physicalWidth'];
397 $width = $params['physicalWidth'];
398 $height = $params['physicalHeight'];
400 $dst_image = imagecreatetruecolor( $width, $height );
402 // Initialise the destination image to transparent instead of
403 // the default solid black, to support PNG and GIF transparency nicely
404 $background = imagecolorallocate( $dst_image, 0, 0, 0 );
405 imagecolortransparent( $dst_image, $background );
406 imagealphablending( $dst_image, false );
408 if ( $colorStyle == 'palette' ) {
409 // Don't resample for paletted GIF images.
410 // It may just uglify them, and completely breaks transparency.
411 imagecopyresized( $dst_image, $src_image,
414 imagesx( $src_image ), imagesy( $src_image ) );
416 imagecopyresampled( $dst_image, $src_image,
419 imagesx( $src_image ), imagesy( $src_image ) );
422 if ( $rotation %
360 != 0 && $rotation %
90 == 0 ) {
423 $rot_image = imagerotate( $dst_image, $rotation, 0 );
424 imagedestroy( $dst_image );
425 $dst_image = $rot_image;
428 imagesavealpha( $dst_image, true );
430 call_user_func( $saveType, $dst_image, $params['dstPath'] );
431 imagedestroy( $dst_image );
432 imagedestroy( $src_image );
434 return false; # No error
438 * Escape a string for ImageMagick's property input (e.g. -set -comment)
439 * See InterpretImageProperties() in magick/property.c
441 function escapeMagickProperty( $s ) {
442 // Double the backslashes
443 $s = str_replace( '\\', '\\\\', $s );
444 // Double the percents
445 $s = str_replace( '%', '%%', $s );
446 // Escape initial - or @
447 if ( strlen( $s ) > 0 && ( $s[0] === '-' ||
$s[0] === '@' ) ) {
454 * Escape a string for ImageMagick's input filenames. See ExpandFilenames()
455 * and GetPathComponent() in magick/utility.c.
457 * This won't work with an initial ~ or @, so input files should be prefixed
458 * with the directory name.
460 * Glob character unescaping is broken in ImageMagick before 6.6.1-5, but
461 * it's broken in a way that doesn't involve trying to convert every file
462 * in a directory, so we're better off escaping and waiting for the bugfix
463 * to filter down to users.
465 * @param $path string The file path
466 * @param $scene string The scene specification, or false if there is none
468 function escapeMagickInput( $path, $scene = false ) {
469 # Die on initial metacharacters (caller should prepend path)
470 $firstChar = substr( $path, 0, 1 );
471 if ( $firstChar === '~' ||
$firstChar === '@' ) {
472 throw new MWException( __METHOD__
. ': cannot escape this path name' );
476 $path = preg_replace( '/[*?\[\]{}]/', '\\\\\0', $path );
478 return $this->escapeMagickPath( $path, $scene );
482 * Escape a string for ImageMagick's output filename. See
483 * InterpretImageFilename() in magick/image.c.
485 function escapeMagickOutput( $path, $scene = false ) {
486 $path = str_replace( '%', '%%', $path );
487 return $this->escapeMagickPath( $path, $scene );
491 * Armour a string against ImageMagick's GetPathComponent(). This is a
492 * helper function for escapeMagickInput() and escapeMagickOutput().
494 * @param $path string The file path
495 * @param $scene string The scene specification, or false if there is none
497 protected function escapeMagickPath( $path, $scene = false ) {
498 # Die on format specifiers (other than drive letters). The regex is
499 # meant to match all the formats you get from "convert -list format"
500 if ( preg_match( '/^([a-zA-Z0-9-]+):/', $path, $m ) ) {
501 if ( wfIsWindows() && is_dir( $m[0] ) ) {
502 // OK, it's a drive letter
503 // ImageMagick has a similar exception, see IsMagickConflict()
505 throw new MWException( __METHOD__
. ': unexpected colon character in path name' );
509 # If there are square brackets, add a do-nothing scene specification
510 # to force a literal interpretation
511 if ( $scene === false ) {
512 if ( strpos( $path, '[' ) !== false ) {
522 * Retrieve the version of the installed ImageMagick
523 * You can use PHPs version_compare() to use this value
524 * Value is cached for one hour.
525 * @return String representing the IM version.
527 protected function getMagickVersion() {
530 $cache = $wgMemc->get( "imagemagick-version" );
532 global $wgImageMagickConvertCommand;
533 $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . ' -version';
534 wfDebug( __METHOD__
. ": Running convert -version\n" );
536 $return = wfShellExec( $cmd, $retval );
537 $x = preg_match( '/Version: ImageMagick ([0-9]*\.[0-9]*\.[0-9]*)/', $return, $matches );
539 wfDebug( __METHOD__
. ": ImageMagick version check failed\n" );
542 $wgMemc->set( "imagemagick-version", $matches[1], 3600 );
548 static function imageJpegWrapper( $dst_image, $thumbPath ) {
549 imageinterlace( $dst_image );
550 imagejpeg( $dst_image, $thumbPath, 95 );
554 function getMetadata( $image, $filename ) {
556 if ( $wgShowEXIF && file_exists( $filename ) ) {
557 $exif = new Exif( $filename );
558 $data = $exif->getFilteredData();
560 $data['MEDIAWIKI_EXIF_VERSION'] = Exif
::version();
561 return serialize( $data );
570 function getMetadataType( $image ) {
574 function isMetadataValid( $image, $metadata ) {
576 if ( !$wgShowEXIF ) {
577 # Metadata disabled and so an empty field is expected
580 if ( $metadata === '0' ) {
581 # Special value indicating that there is no EXIF data in the file
584 wfSuppressWarnings();
585 $exif = unserialize( $metadata );
587 if ( !isset( $exif['MEDIAWIKI_EXIF_VERSION'] ) ||
588 $exif['MEDIAWIKI_EXIF_VERSION'] != Exif
::version() )
591 wfDebug( __METHOD__
. ": wrong version\n" );
598 * Get a list of EXIF metadata items which should be displayed when
599 * the metadata table is collapsed.
601 * @return array of strings
604 function visibleMetadataFields() {
606 $lines = explode( "\n", wfMsgForContent( 'metadata-fields' ) );
607 foreach ( $lines as $line ) {
609 if ( preg_match( '/^\\*\s*(.*?)\s*$/', $line, $matches ) ) {
610 $fields[] = $matches[1];
613 $fields = array_map( 'strtolower', $fields );
617 function formatMetadata( $image ) {
619 'visible' => array(),
620 'collapsed' => array()
622 $metadata = $image->getMetadata();
626 $exif = unserialize( $metadata );
630 unset( $exif['MEDIAWIKI_EXIF_VERSION'] );
631 $format = new FormatExif( $exif );
633 $formatted = $format->getFormattedData();
634 // Sort fields into visible and collapsed
635 $visibleFields = $this->visibleMetadataFields();
636 foreach ( $formatted as $name => $value ) {
637 $tag = strtolower( $name );
638 self
::addMeta( $result,
639 in_array( $tag, $visibleFields ) ?
'visible' : 'collapsed',
649 * Try to read out the orientation of the file and return the angle that
650 * the file needs to be rotated to be viewed
653 * @return int 0, 90, 180 or 270
655 public function getRotation( $file ) {
656 $data = $file->getMetadata();
660 $data = unserialize( $data );
661 if ( isset( $data['Orientation'] ) ) {
662 # See http://sylvana.net/jpegcrop/exif_orientation.html
663 switch ( $data['Orientation'] ) {
677 * Returns whether the current scaler supports rotation (im and gd do)
681 public function canRotate() {
682 $scaler = $this->getScalerType( null, false );
683 return $scaler == 'im' ||
$scaler == 'gd';
687 * Rerurns whether the file needs to be rendered. Returns true if the
688 * file requires rotation and we are able to rotate it.
693 public function mustRender( $file ) {
694 return $this->canRotate() && $this->getRotation( $file ) != 0;