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 global $wgCustomConvertCommand;
71 if ( !$this->normaliseParams( $image, $params ) ) {
72 return new TransformParameterError( $params );
74 # Create a parameter array to pass to the scaler
75 $scalerParams = array(
76 # The size to which the image will be resized
77 'physicalWidth' => $params['physicalWidth'],
78 'physicalHeight' => $params['physicalHeight'],
79 'physicalDimensions' => "{$params['physicalWidth']}x{$params['physicalHeight']}",
80 # The size of the image on the page
81 'clientWidth' => $params['width'],
82 'clientHeight' => $params['height'],
83 # Comment as will be added to the EXIF of the thumbnail
84 'comment' => isset( $params['descriptionUrl'] ) ?
85 "File source: {$params['descriptionUrl']}" : '',
86 # Properties of the original image
87 'srcWidth' => $image->getWidth(),
88 'srcHeight' => $image->getHeight(),
89 'mimeType' => $image->getMimeType(),
90 'srcPath' => $image->getPath(),
91 'dstPath' => $dstPath,
94 wfDebug( __METHOD__
. ": creating {$scalerParams['physicalDimensions']} thumbnail at $dstPath\n" );
96 if ( !$image->mustRender() &&
97 $scalerParams['physicalWidth'] == $scalerParams['srcWidth']
98 && $scalerParams['physicalHeight'] == $scalerParams['srcHeight'] ) {
100 # normaliseParams (or the user) wants us to return the unscaled image
101 wfDebug( __METHOD__
. ": returning unscaled image\n" );
102 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
105 # Determine scaler type
106 $scaler = $this->getScalerType( $dstPath );
107 wfDebug( __METHOD__
. ": scaler $scaler\n" );
109 if ( $scaler == 'client' ) {
110 # Client-side image scaling, use the source URL
111 # Using the destination URL in a TRANSFORM_LATER request would be incorrect
112 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
115 if ( $flags & self
::TRANSFORM_LATER
) {
116 wfDebug( __METHOD__
. ": Transforming later per flags.\n" );
117 return new ThumbnailImage( $image, $dstUrl, $scalerParams['clientWidth'],
118 $scalerParams['clientHeight'], $dstPath );
121 # Try to make a target path for the thumbnail
122 if ( !wfMkdirParents( dirname( $dstPath ) ) ) {
123 wfDebug( __METHOD__
. ": Unable to create thumbnail destination directory, falling back to client scaling\n" );
124 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
129 $err = $this->transformImageMagick( $image, $scalerParams );
132 $err = $this->transformCustom( $image, $scalerParams );
136 $err = $this->transformGd( $image, $scalerParams );
140 # Remove the file if a zero-byte thumbnail was created, or if there was an error
141 $removed = $this->removeBadFile( $dstPath, (bool)$err );
143 # transform returned MediaTransforError
145 } elseif ( $removed ) {
146 # Thumbnail was zero-byte and had to be removed
147 return new MediaTransformError( 'thumbnail_error',
148 $scalerParams['clientWidth'], $scalerParams['clientHeight'] );
150 return new ThumbnailImage( $image, $dstUrl, $scalerParams['clientWidth'],
151 $scalerParams['clientHeight'], $dstPath );
156 * Returns which scaler type should be used. Creates parent directories
157 * for $dstPath and returns 'client' on error
159 * @return string client,im,custom,gd
161 protected function getScalerType( $dstPath, $checkDstPath = true ) {
162 global $wgUseImageResize, $wgUseImageMagick, $wgCustomConvertCommand;
164 if ( !$dstPath && $checkDstPath ) {
165 # No output path available, client side scaling only
167 } elseif ( !$wgUseImageResize ) {
169 } elseif ( $wgUseImageMagick ) {
171 } elseif ( $wgCustomConvertCommand ) {
173 } elseif ( function_exists( 'imagecreatetruecolor' ) ) {
179 if ( $scaler != 'client' && $dstPath ) {
180 if ( !wfMkdirParents( dirname( $dstPath ) ) ) {
181 # Unable to create a path for the thumbnail
189 * Get a ThumbnailImage that respresents an image that will be scaled
192 * @param $image File File associated with this thumbnail
193 * @param $params array Array with scaler params
194 * @return ThumbnailImage
196 protected function getClientScalingThumbnailImage( $image, $params ) {
197 return new ThumbnailImage( $image, $image->getURL(),
198 $params['clientWidth'], $params['clientHeight'], $params['srcPath'] );
202 * Transform an image using ImageMagick
204 * @param $image File File associated with this thumbnail
205 * @param $params array Array with scaler params
207 * @return MediaTransformError Error object if error occured, false (=no error) otherwise
209 protected function transformImageMagick( $image, $params ) {
211 global $wgSharpenReductionThreshold, $wgSharpenParameter,
212 $wgMaxAnimatedGifArea,
213 $wgImageMagickTempDir, $wgImageMagickConvertCommand;
219 $animation_post = '';
221 if ( $params['mimeType'] == 'image/jpeg' ) {
222 $quality = "-quality 80"; // 80%
223 # Sharpening, see bug 6193
224 if ( ( $params['physicalWidth'] +
$params['physicalHeight'] )
225 / ( $params['srcWidth'] +
$params['srcHeight'] )
226 < $wgSharpenReductionThreshold ) {
227 $sharpen = "-sharpen " . wfEscapeShellArg( $wgSharpenParameter );
229 // JPEG decoder hint to reduce memory, available since IM 6.5.6-2
230 $decoderHint = "-define jpeg:size={$params['physicalDimensions']}";
232 } elseif ( $params['mimeType'] == 'image/png' ) {
233 $quality = "-quality 95"; // zlib 9, adaptive filtering
235 } elseif ( $params['mimeType'] == 'image/gif' ) {
236 if ( $this->getImageArea( $image, $params['srcWidth'],
237 $params['srcHeight'] ) > $wgMaxAnimatedGifArea ) {
238 // Extract initial frame only; we're so big it'll
239 // be a total drag. :P
242 } elseif ( $this->isAnimatedImage( $image ) ) {
243 // Coalesce is needed to scale animated GIFs properly (bug 1017).
244 $animation_pre = '-coalesce';
245 // We optimize the output, but -optimize is broken,
246 // use optimizeTransparency instead (bug 11822)
247 if ( version_compare( $this->getMagickVersion(), "6.3.5" ) >= 0 ) {
248 $animation_post = '-fuzz 5% -layers optimizeTransparency +map';
253 // Use one thread only, to avoid deadlock bugs on OOM
254 $env = array( 'OMP_NUM_THREADS' => 1 );
255 if ( strval( $wgImageMagickTempDir ) !== '' ) {
256 $env['MAGICK_TMPDIR'] = $wgImageMagickTempDir;
260 wfEscapeShellArg( $wgImageMagickConvertCommand ) .
261 // Specify white background color, will be used for transparent images
262 // in Internet Explorer/Windows instead of default black.
263 " {$quality} -background white" .
265 wfEscapeShellArg( $this->escapeMagickInput( $params['srcPath'], $scene ) ) .
266 " {$animation_pre}" .
267 // For the -thumbnail option a "!" is needed to force exact size,
268 // or ImageMagick may decide your ratio is wrong and slice off
270 " -thumbnail " . wfEscapeShellArg( "{$params['physicalDimensions']}!" ) .
271 // Add the source url as a comment to the thumb, but don't add the flag if there's no comment
272 ( $params['comment'] !== ''
273 ?
" -set comment " . wfEscapeShellArg( $this->escapeMagickProperty( $params['comment'] ) )
275 " -depth 8 $sharpen -auto-orient" .
276 " {$animation_post} " .
277 wfEscapeShellArg( $this->escapeMagickOutput( $params['dstPath'] ) ) . " 2>&1";
279 wfDebug( __METHOD__
. ": running ImageMagick: $cmd\n" );
280 wfProfileIn( 'convert' );
282 $err = wfShellExec( $cmd, $retval, $env );
283 wfProfileOut( 'convert' );
285 if ( $retval !== 0 ) {
286 $this->logErrorForExternalProcess( $retval, $err, $cmd );
287 return $this->getMediaTransformError( $params, $err );
290 return false; # No error
294 * Transform an image using a custom command
296 * @param $image File File associated with this thumbnail
297 * @param $params array Array with scaler params
299 * @return MediaTransformError Error object if error occured, false (=no error) otherwise
301 protected function transformCustom( $image, $params ) {
302 # Use a custom convert command
303 global $wgCustomConvertCommand;
305 # Variables: %s %d %w %h
306 $src = wfEscapeShellArg( $params['srcPath'] );
307 $dst = wfEscapeShellArg( $params['dstPath'] );
308 $cmd = $wgCustomConvertCommand;
309 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
310 $cmd = str_replace( '%h', $params['physicalHeight'],
311 str_replace( '%w', $params['physicalWidth'], $cmd ) ); # Size
312 wfDebug( __METHOD__
. ": Running custom convert command $cmd\n" );
313 wfProfileIn( 'convert' );
315 $err = wfShellExec( $cmd, $retval );
316 wfProfileOut( 'convert' );
318 if ( $retval !== 0 ) {
319 $this->logErrorForExternalProcess( $retval, $err, $cmd );
320 return $this->getMediaTransformError( $params, $err );
322 return false; # No error
326 * Log an error that occured in an external process
332 protected function logErrorForExternalProcess( $retval, $err, $cmd ) {
333 wfDebugLog( 'thumbnail',
334 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
335 wfHostname(), $retval, trim( $err ), $cmd ) );
338 * Get a MediaTransformError with error 'thumbnail_error'
340 * @param $params array Parameter array as passed to the transform* functions
341 * @param $errMsg string Error message
342 * @return MediaTransformError
344 protected function getMediaTransformError( $params, $errMsg ) {
345 return new MediaTransformError( 'thumbnail_error', $params['clientWidth'],
346 $params['clientHeight'], $errMsg );
350 * Transform an image using the built in GD library
352 * @param $image File File associated with this thumbnail
353 * @param $params array Array with scaler params
355 * @return MediaTransformError Error object if error occured, false (=no error) otherwise
357 protected function transformGd( $image, $params ) {
358 # Use PHP's builtin GD library functions.
360 # First find out what kind of file this is, and select the correct
361 # input routine for this.
364 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
365 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( __CLASS__
, 'imageJpegWrapper' ) ),
366 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
367 'image/vnd.wap.wbmp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
368 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
370 if ( !isset( $typemap[$params['mimeType']] ) ) {
371 $err = 'Image type not supported';
373 $errMsg = wfMsg ( 'thumbnail_image-type' );
374 return $this->getMediaTransformError( $params, $errMsg );
376 list( $loader, $colorStyle, $saveType ) = $typemap[$params['mimeType']];
378 if ( !function_exists( $loader ) ) {
379 $err = "Incomplete GD library configuration: missing function $loader";
381 $errMsg = wfMsg ( 'thumbnail_gd-library', $loader );
382 return $this->getMediaTransformError( $params, $errMsg );
385 if ( !file_exists( $params['srcPath'] ) ) {
386 $err = "File seems to be missing: {$params['srcPath']}";
388 $errMsg = wfMsg ( 'thumbnail_image-missing', $params['srcPath'] );
389 return $this->getMediaTransformError( $params, $errMsg );
392 $src_image = call_user_func( $loader, $params['srcPath'] );
393 $rotation = $this->getRotation( $image );
394 if ( $rotation == 90 ||
$rotation == 270 ) {
395 # We'll resize before rotation, so swap the dimensions again
396 $width = $params['physicalHeight'];
397 $height = $params['physicalWidth'];
399 $width = $params['physicalWidth'];
400 $height = $params['physicalHeight'];
402 $dst_image = imagecreatetruecolor( $width, $height );
404 // Initialise the destination image to transparent instead of
405 // the default solid black, to support PNG and GIF transparency nicely
406 $background = imagecolorallocate( $dst_image, 0, 0, 0 );
407 imagecolortransparent( $dst_image, $background );
408 imagealphablending( $dst_image, false );
410 if ( $colorStyle == 'palette' ) {
411 // Don't resample for paletted GIF images.
412 // It may just uglify them, and completely breaks transparency.
413 imagecopyresized( $dst_image, $src_image,
416 imagesx( $src_image ), imagesy( $src_image ) );
418 imagecopyresampled( $dst_image, $src_image,
421 imagesx( $src_image ), imagesy( $src_image ) );
424 if ( $rotation %
360 != 0 && $rotation %
90 == 0 ) {
425 $rot_image = imagerotate( $dst_image, $rotation, 0 );
426 imagedestroy( $dst_image );
427 $dst_image = $rot_image;
430 imagesavealpha( $dst_image, true );
432 call_user_func( $saveType, $dst_image, $params['dstPath'] );
433 imagedestroy( $dst_image );
434 imagedestroy( $src_image );
436 return false; # No error
440 * Escape a string for ImageMagick's property input (e.g. -set -comment)
441 * See InterpretImageProperties() in magick/property.c
443 function escapeMagickProperty( $s ) {
444 // Double the backslashes
445 $s = str_replace( '\\', '\\\\', $s );
446 // Double the percents
447 $s = str_replace( '%', '%%', $s );
448 // Escape initial - or @
449 if ( strlen( $s ) > 0 && ( $s[0] === '-' ||
$s[0] === '@' ) ) {
456 * Escape a string for ImageMagick's input filenames. See ExpandFilenames()
457 * and GetPathComponent() in magick/utility.c.
459 * This won't work with an initial ~ or @, so input files should be prefixed
460 * with the directory name.
462 * Glob character unescaping is broken in ImageMagick before 6.6.1-5, but
463 * it's broken in a way that doesn't involve trying to convert every file
464 * in a directory, so we're better off escaping and waiting for the bugfix
465 * to filter down to users.
467 * @param $path string The file path
468 * @param $scene string The scene specification, or false if there is none
470 function escapeMagickInput( $path, $scene = false ) {
471 # Die on initial metacharacters (caller should prepend path)
472 $firstChar = substr( $path, 0, 1 );
473 if ( $firstChar === '~' ||
$firstChar === '@' ) {
474 throw new MWException( __METHOD__
. ': cannot escape this path name' );
478 $path = preg_replace( '/[*?\[\]{}]/', '\\\\\0', $path );
480 return $this->escapeMagickPath( $path, $scene );
484 * Escape a string for ImageMagick's output filename. See
485 * InterpretImageFilename() in magick/image.c.
487 function escapeMagickOutput( $path, $scene = false ) {
488 $path = str_replace( '%', '%%', $path );
489 return $this->escapeMagickPath( $path, $scene );
493 * Armour a string against ImageMagick's GetPathComponent(). This is a
494 * helper function for escapeMagickInput() and escapeMagickOutput().
496 * @param $path string The file path
497 * @param $scene string The scene specification, or false if there is none
499 protected function escapeMagickPath( $path, $scene = false ) {
500 # Die on format specifiers (other than drive letters). The regex is
501 # meant to match all the formats you get from "convert -list format"
502 if ( preg_match( '/^([a-zA-Z0-9-]+):/', $path, $m ) ) {
503 if ( wfIsWindows() && is_dir( $m[0] ) ) {
504 // OK, it's a drive letter
505 // ImageMagick has a similar exception, see IsMagickConflict()
507 throw new MWException( __METHOD__
. ': unexpected colon character in path name' );
511 # If there are square brackets, add a do-nothing scene specification
512 # to force a literal interpretation
513 if ( $scene === false ) {
514 if ( strpos( $path, '[' ) !== false ) {
524 * Retrieve the version of the installed ImageMagick
525 * You can use PHPs version_compare() to use this value
526 * Value is cached for one hour.
527 * @return String representing the IM version.
529 protected function getMagickVersion() {
532 $cache = $wgMemc->get( "imagemagick-version" );
534 global $wgImageMagickConvertCommand;
535 $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . ' -version';
536 wfDebug( __METHOD__
. ": Running convert -version\n" );
538 $return = wfShellExec( $cmd, $retval );
539 $x = preg_match( '/Version: ImageMagick ([0-9]*\.[0-9]*\.[0-9]*)/', $return, $matches );
541 wfDebug( __METHOD__
. ": ImageMagick version check failed\n" );
544 $wgMemc->set( "imagemagick-version", $matches[1], 3600 );
550 static function imageJpegWrapper( $dst_image, $thumbPath ) {
551 imageinterlace( $dst_image );
552 imagejpeg( $dst_image, $thumbPath, 95 );
556 function getMetadata( $image, $filename ) {
558 if ( $wgShowEXIF && file_exists( $filename ) ) {
559 $exif = new Exif( $filename );
560 $data = $exif->getFilteredData();
562 $data['MEDIAWIKI_EXIF_VERSION'] = Exif
::version();
563 return serialize( $data );
572 function getMetadataType( $image ) {
576 function isMetadataValid( $image, $metadata ) {
578 if ( !$wgShowEXIF ) {
579 # Metadata disabled and so an empty field is expected
582 if ( $metadata === '0' ) {
583 # Special value indicating that there is no EXIF data in the file
586 wfSuppressWarnings();
587 $exif = unserialize( $metadata );
589 if ( !isset( $exif['MEDIAWIKI_EXIF_VERSION'] ) ||
590 $exif['MEDIAWIKI_EXIF_VERSION'] != Exif
::version() )
593 wfDebug( __METHOD__
. ": wrong version\n" );
600 * Get a list of EXIF metadata items which should be displayed when
601 * the metadata table is collapsed.
603 * @return array of strings
606 function visibleMetadataFields() {
608 $lines = explode( "\n", wfMsgForContent( 'metadata-fields' ) );
609 foreach ( $lines as $line ) {
611 if ( preg_match( '/^\\*\s*(.*?)\s*$/', $line, $matches ) ) {
612 $fields[] = $matches[1];
615 $fields = array_map( 'strtolower', $fields );
619 function formatMetadata( $image ) {
621 'visible' => array(),
622 'collapsed' => array()
624 $metadata = $image->getMetadata();
628 $exif = unserialize( $metadata );
632 unset( $exif['MEDIAWIKI_EXIF_VERSION'] );
633 $format = new FormatExif( $exif );
635 $formatted = $format->getFormattedData();
636 // Sort fields into visible and collapsed
637 $visibleFields = $this->visibleMetadataFields();
638 foreach ( $formatted as $name => $value ) {
639 $tag = strtolower( $name );
640 self
::addMeta( $result,
641 in_array( $tag, $visibleFields ) ?
'visible' : 'collapsed',
651 * Try to read out the orientation of the file and return the angle that
652 * the file needs to be rotated to be viewed
655 * @return int 0, 90, 180 or 270
657 public function getRotation( $file ) {
658 $data = $file->getMetadata();
662 $data = unserialize( $data );
663 if ( isset( $data['Orientation'] ) ) {
664 # See http://sylvana.net/jpegcrop/exif_orientation.html
665 switch ( $data['Orientation'] ) {
679 * Returns whether the current scaler supports rotation (im and gd do)
683 public function canRotate() {
684 $scaler = $this->getScalerType( null, false );
685 return $scaler == 'im' ||
$scaler == 'gd';
689 * Rerurns whether the file needs to be rendered. Returns true if the
690 * file requires rotation and we are able to rotate it.
695 public function mustRender( $file ) {
696 return $this->canRotate() && $this->getRotation( $file ) != 0;