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 # Don't make an image bigger than the source
26 $params['physicalWidth'] = $params['width'];
27 $params['physicalHeight'] = $params['height'];
29 if ( $params['physicalWidth'] >= $srcWidth ) {
30 $params['physicalWidth'] = $srcWidth;
31 $params['physicalHeight'] = $srcHeight;
32 # Skip scaling limit checks if no scaling is required
33 if ( !$image->mustRender() )
37 # Don't thumbnail an image so big that it will fill hard drives and send servers into swap
38 # JPEG has the handy property of allowing thumbnailing without full decompression, so we make
39 # an exception for it.
40 # FIXME: This actually only applies to ImageMagick
41 if ( $mimeType !== 'image/jpeg' &&
42 $srcWidth * $srcHeight > $wgMaxImageArea )
51 // Function that returns the number of pixels to be thumbnailed.
52 // Intended for animated GIFs to multiply by the number of frames.
53 function getImageArea( $image, $width, $height ) {
54 return $width * $height;
57 function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
58 global $wgUseImageMagick;
59 global $wgCustomConvertCommand, $wgUseImageResize;
61 if ( !$this->normaliseParams( $image, $params ) ) {
62 return new TransformParameterError( $params );
64 # Create a parameter array to pass to the scaler
65 $scalerParams = array(
66 # The size to which the image will be resized
67 'physicalWidth' => $params['physicalWidth'],
68 'physicalHeight' => $params['physicalHeight'],
69 'physicalDimensions' => "{$params['physicalWidth']}x{$params['physicalHeight']}",
70 # The size of the image on the page
71 'clientWidth' => $params['width'],
72 'clientHeight' => $params['height'],
73 # Comment as will be added to the EXIF of the thumbnail
74 'comment' => isset( $params['descriptionUrl'] ) ?
75 "File source: {$params['descriptionUrl']}" : '',
76 # Properties of the original image
77 'srcWidth' => $image->getWidth(),
78 'srcHeight' => $image->getHeight(),
79 'mimeType' => $image->getMimeType(),
80 'srcPath' => $image->getPath(),
81 'dstPath' => $dstPath,
84 wfDebug( __METHOD__
. ": creating {$scalerParams['physicalDimensions']} thumbnail at $dstPath\n" );
86 if ( !$image->mustRender() &&
87 $scalerParams['physicalWidth'] == $scalerParams['srcWidth']
88 && $scalerParams['physicalHeight'] == $scalerParams['srcHeight'] ) {
90 # normaliseParams (or the user) wants us to return the unscaled image
91 wfDebug( __METHOD__
. ": returning unscaled image\n" );
92 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
95 # Determine scaler type
97 # No output path available, client side scaling only
99 } elseif ( !$wgUseImageResize ) {
101 } elseif ( $wgUseImageMagick ) {
103 } elseif ( $wgCustomConvertCommand ) {
105 } elseif ( function_exists( 'imagecreatetruecolor' ) ) {
110 wfDebug( __METHOD__
. ": scaler $scaler\n" );
112 if ( $scaler == 'client' ) {
113 # Client-side image scaling, use the source URL
114 # Using the destination URL in a TRANSFORM_LATER request would be incorrect
115 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
118 if ( $flags & self
::TRANSFORM_LATER
) {
119 wfDebug( __METHOD__
. ": Transforming later per flags.\n" );
120 return new ThumbnailImage( $image, $dstUrl, $scalerParams['clientWidth'],
121 $scalerParams['clientHeight'], $dstPath );
124 # Try to make a target path for the thumbnail
125 if ( !wfMkdirParents( dirname( $dstPath ) ) ) {
126 wfDebug( __METHOD__
. ": Unable to create thumbnail destination directory, falling back to client scaling\n" );
127 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
132 $err = $this->transformImageMagick( $image, $scalerParams );
135 $err = $this->transformCustom( $image, $scalerParams );
139 $err = $this->transformGd( $image, $scalerParams );
143 # Remove the file if a zero-byte thumbnail was created, or if there was an error
144 $removed = $this->removeBadFile( $dstPath, (bool)$err );
146 # transform returned MediaTransforError
148 } elseif ( $removed ) {
149 # Thumbnail was zero-byte and had to be removed
150 return new MediaTransformError( 'thumbnail_error',
151 $scalerParams['clientWidth'], $scalerParams['clientHeight'] );
153 return new ThumbnailImage( $image, $dstUrl, $scalerParams['clientWidth'],
154 $scalerParams['clientHeight'], $dstPath );
159 * Get a ThumbnailImage that respresents an image that will be scaled
162 * @param $image File File associated with this thumbnail
163 * @param $params array Array with scaler params
164 * @return ThumbnailImage
166 protected function getClientScalingThumbnailImage( $image, $params ) {
167 return new ThumbnailImage( $image, $image->getURL(),
168 $params['clientWidth'], $params['clientHeight'], $params['srcPath'] );
172 * Transform an image using ImageMagick
174 * @param $image File File associated with this thumbnail
175 * @param $params array Array with scaler params
177 * @return MediaTransformError Error object if error occured, false (=no error) otherwise
179 protected function transformImageMagick( $image, $params ) {
181 global $wgSharpenReductionThreshold, $wgSharpenParameter,
182 $wgMaxAnimatedGifArea,
183 $wgImageMagickTempDir, $wgImageMagickConvertCommand;
189 $animation_post = '';
191 if ( $params['mimeType'] == 'image/jpeg' ) {
192 $quality = "-quality 80"; // 80%
193 # Sharpening, see bug 6193
194 if ( ( $params['physicalWidth'] +
$params['physicalHeight'] )
195 / ( $params['srcWidth'] +
$params['srcHeight'] )
196 < $wgSharpenReductionThreshold ) {
197 $sharpen = "-sharpen " . wfEscapeShellArg( $wgSharpenParameter );
199 // JPEG decoder hint to reduce memory, available since IM 6.5.6-2
200 $decoderHint = "-define jpeg:size={$params['physicalDimensions']}";
202 } elseif ( $params['mimeType'] == 'image/png' ) {
203 $quality = "-quality 95"; // zlib 9, adaptive filtering
205 } elseif ( $params['mimeType'] == 'image/gif' ) {
206 if ( $this->getImageArea( $image, $params['srcWidth'],
207 $params['srcHeight'] ) > $wgMaxAnimatedGifArea ) {
208 // Extract initial frame only; we're so big it'll
209 // be a total drag. :P
212 } elseif ( $this->isAnimatedImage( $image ) ) {
213 // Coalesce is needed to scale animated GIFs properly (bug 1017).
214 $animation_pre = '-coalesce';
215 // We optimize the output, but -optimize is broken,
216 // use optimizeTransparency instead (bug 11822)
217 if ( version_compare( $this->getMagickVersion(), "6.3.5" ) >= 0 ) {
218 $animation_post = '-fuzz 5% -layers optimizeTransparency +map';
223 // Use one thread only, to avoid deadlock bugs on OOM
224 $env = array( 'OMP_NUM_THREADS' => 1 );
225 if ( strval( $wgImageMagickTempDir ) !== '' ) {
226 $env['MAGICK_TMPDIR'] = $wgImageMagickTempDir;
230 wfEscapeShellArg( $wgImageMagickConvertCommand ) .
231 // Specify white background color, will be used for transparent images
232 // in Internet Explorer/Windows instead of default black.
233 " {$quality} -background white" .
235 wfEscapeShellArg( $this->escapeMagickInput( $params['srcPath'], $scene ) ) .
236 " {$animation_pre}" .
237 // For the -thumbnail option a "!" is needed to force exact size,
238 // or ImageMagick may decide your ratio is wrong and slice off
240 " -thumbnail " . wfEscapeShellArg( "{$params['physicalDimensions']}!" ) .
241 // Add the source url as a comment to the thumb, but don't add the flag if there's no comment
242 $params['comment'] !== ''
243 ?
" -set comment " . wfEscapeShellArg( $this->escapeMagickProperty( $params['comment'] ) )
245 " -depth 8 $sharpen" .
246 " {$animation_post} " .
247 wfEscapeShellArg( $this->escapeMagickOutput( $params['dstPath'] ) ) . " 2>&1";
249 wfDebug( __METHOD__
. ": running ImageMagick: $cmd\n" );
250 wfProfileIn( 'convert' );
252 $err = wfShellExec( $cmd, $retval, $env );
253 wfProfileOut( 'convert' );
255 if ( $retval !== 0 ) {
256 $this->logErrorForExternalProcess( $retval, $err, $cmd );
257 return $this->getMediaTransformError( $params, $err );
260 return false; # No error
264 * Transform an image using a custom command
266 * @param $image File File associated with this thumbnail
267 * @param $params array Array with scaler params
269 * @return MediaTransformError Error object if error occured, false (=no error) otherwise
271 protected function transformCustom( $image, $params ) {
272 # Use a custom convert command
273 global $wgCustomConvertCommand;
275 # Variables: %s %d %w %h
276 $src = wfEscapeShellArg( $params['srcPath'] );
277 $dst = wfEscapeShellArg( $params['dstPath'] );
278 $cmd = $wgCustomConvertCommand;
279 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
280 $cmd = str_replace( '%h', $params['physicalHeight'],
281 str_replace( '%w', $params['physicalWidth'], $cmd ) ); # Size
282 wfDebug( __METHOD__
. ": Running custom convert command $cmd\n" );
283 wfProfileIn( 'convert' );
285 $err = wfShellExec( $cmd, $retval );
286 wfProfileOut( 'convert' );
288 if ( $retval !== 0 ) {
289 $this->logErrorForExternalProcess( $retval, $err, $cmd );
290 return $this->getMediaTransformError( $params, $err );
292 return false; # No error
296 * Log an error that occured in an external process
302 protected function logErrorForExternalProcess( $retval, $err, $cmd ) {
303 wfDebugLog( 'thumbnail',
304 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
305 wfHostname(), $retval, trim( $err ), $cmd ) );
308 * Get a MediaTransformError with error 'thumbnail_error'
310 * @param $params array Paramter array as passed to the transform* functions
311 * @param $errMsg string Error message
312 * @return MediaTransformError
314 protected function getMediaTransformError( $params, $errMsg ) {
315 return new MediaTransformError( 'thumbnail_error', $params['clientWidth'],
316 $params['clientHeight'], $errMsg );
320 * Transform an image using the built in GD library
322 * @param $image File File associated with this thumbnail
323 * @param $params array Array with scaler params
325 * @return MediaTransformError Error object if error occured, false (=no error) otherwise
327 protected function transformGd( $image, $params ) {
328 # Use PHP's builtin GD library functions.
330 # First find out what kind of file this is, and select the correct
331 # input routine for this.
334 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
335 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( __CLASS__
, 'imageJpegWrapper' ) ),
336 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
337 'image/vnd.wap.wbmp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
338 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
340 if ( !isset( $typemap[$params['mimeType']] ) ) {
341 $err = 'Image type not supported';
343 $errMsg = wfMsg ( 'thumbnail_image-type' );
344 return $this->getMediaTransformError( $params, $errMsg );
346 list( $loader, $colorStyle, $saveType ) = $typemap[$params['mimeType']];
348 if ( !function_exists( $loader ) ) {
349 $err = "Incomplete GD library configuration: missing function $loader";
351 $errMsg = wfMsg ( 'thumbnail_gd-library', $loader );
352 return $this->getMediaTransformError( $params, $errMsg );
355 if ( !file_exists( $params['srcPath'] ) ) {
356 $err = "File seems to be missing: {$params['srcPath']}";
358 $errMsg = wfMsg ( 'thumbnail_image-missing', $params['srcPath'] );
359 return $this->getMediaTransformError( $params, $errMsg );
362 $src_image = call_user_func( $loader, $params['srcPath'] );
363 $dst_image = imagecreatetruecolor( $params['physicalWidth'],
364 $params['physicalHeight'] );
366 // Initialise the destination image to transparent instead of
367 // the default solid black, to support PNG and GIF transparency nicely
368 $background = imagecolorallocate( $dst_image, 0, 0, 0 );
369 imagecolortransparent( $dst_image, $background );
370 imagealphablending( $dst_image, false );
372 if ( $colorStyle == 'palette' ) {
373 // Don't resample for paletted GIF images.
374 // It may just uglify them, and completely breaks transparency.
375 imagecopyresized( $dst_image, $src_image,
377 $params['physicalWidth'], $params['physicalHeight'],
378 imagesx( $src_image ), imagesy( $src_image ) );
380 imagecopyresampled( $dst_image, $src_image,
382 $params['physicalWidth'], $params['physicalHeight'],
383 imagesx( $src_image ), imagesy( $src_image ) );
386 imagesavealpha( $dst_image, true );
388 call_user_func( $saveType, $dst_image, $params['dstPath'] );
389 imagedestroy( $dst_image );
390 imagedestroy( $src_image );
392 return false; # No error
396 * Escape a string for ImageMagick's property input (e.g. -set -comment)
397 * See InterpretImageProperties() in magick/property.c
399 function escapeMagickProperty( $s ) {
400 // Double the backslashes
401 $s = str_replace( '\\', '\\\\', $s );
402 // Double the percents
403 $s = str_replace( '%', '%%', $s );
404 // Escape initial - or @
405 if ( strlen( $s ) > 0 && ( $s[0] === '-' ||
$s[0] === '@' ) ) {
412 * Escape a string for ImageMagick's input filenames. See ExpandFilenames()
413 * and GetPathComponent() in magick/utility.c.
415 * This won't work with an initial ~ or @, so input files should be prefixed
416 * with the directory name.
418 * Glob character unescaping is broken in ImageMagick before 6.6.1-5, but
419 * it's broken in a way that doesn't involve trying to convert every file
420 * in a directory, so we're better off escaping and waiting for the bugfix
421 * to filter down to users.
423 * @param $path string The file path
424 * @param $scene string The scene specification, or false if there is none
426 function escapeMagickInput( $path, $scene = false ) {
427 # Die on initial metacharacters (caller should prepend path)
428 $firstChar = substr( $path, 0, 1 );
429 if ( $firstChar === '~' ||
$firstChar === '@' ) {
430 throw new MWException( __METHOD__
. ': cannot escape this path name' );
434 $path = preg_replace( '/[*?\[\]{}]/', '\\\\\0', $path );
436 return $this->escapeMagickPath( $path, $scene );
440 * Escape a string for ImageMagick's output filename. See
441 * InterpretImageFilename() in magick/image.c.
443 function escapeMagickOutput( $path, $scene = false ) {
444 $path = str_replace( '%', '%%', $path );
445 return $this->escapeMagickPath( $path, $scene );
449 * Armour a string against ImageMagick's GetPathComponent(). This is a
450 * helper function for escapeMagickInput() and escapeMagickOutput().
452 * @param $path string The file path
453 * @param $scene string The scene specification, or false if there is none
455 protected function escapeMagickPath( $path, $scene = false ) {
456 # Die on format specifiers (other than drive letters). The regex is
457 # meant to match all the formats you get from "convert -list format"
458 if ( preg_match( '/^([a-zA-Z0-9-]+):/', $path, $m ) ) {
459 if ( wfIsWindows() && is_dir( $m[0] ) ) {
460 // OK, it's a drive letter
461 // ImageMagick has a similar exception, see IsMagickConflict()
463 throw new MWException( __METHOD__
. ': unexpected colon character in path name' );
467 # If there are square brackets, add a do-nothing scene specification
468 # to force a literal interpretation
469 if ( $scene === false ) {
470 if ( strpos( $path, '[' ) !== false ) {
480 * Retrieve the version of the installed ImageMagick
481 * You can use PHPs version_compare() to use this value
482 * Value is cached for one hour.
483 * @return String representing the IM version.
485 protected function getMagickVersion() {
488 $cache = $wgMemc->get( "imagemagick-version" );
490 global $wgImageMagickConvertCommand;
491 $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . ' -version';
492 wfDebug( __METHOD__
. ": Running convert -version\n" );
494 $return = wfShellExec( $cmd, $retval );
495 $x = preg_match( '/Version: ImageMagick ([0-9]*\.[0-9]*\.[0-9]*)/', $return, $matches );
497 wfDebug( __METHOD__
. ": ImageMagick version check failed\n" );
500 $wgMemc->set( "imagemagick-version", $matches[1], 3600 );
506 static function imageJpegWrapper( $dst_image, $thumbPath ) {
507 imageinterlace( $dst_image );
508 imagejpeg( $dst_image, $thumbPath, 95 );
512 function getMetadata( $image, $filename ) {
514 if ( $wgShowEXIF && file_exists( $filename ) ) {
515 $exif = new Exif( $filename );
516 $data = $exif->getFilteredData();
518 $data['MEDIAWIKI_EXIF_VERSION'] = Exif
::version();
519 return serialize( $data );
528 function getMetadataType( $image ) {
532 function isMetadataValid( $image, $metadata ) {
534 if ( !$wgShowEXIF ) {
535 # Metadata disabled and so an empty field is expected
538 if ( $metadata === '0' ) {
539 # Special value indicating that there is no EXIF data in the file
542 wfSuppressWarnings();
543 $exif = unserialize( $metadata );
545 if ( !isset( $exif['MEDIAWIKI_EXIF_VERSION'] ) ||
546 $exif['MEDIAWIKI_EXIF_VERSION'] != Exif
::version() )
549 wfDebug( __METHOD__
. ": wrong version\n" );
556 * Get a list of EXIF metadata items which should be displayed when
557 * the metadata table is collapsed.
559 * @return array of strings
562 function visibleMetadataFields() {
564 $lines = explode( "\n", wfMsgForContent( 'metadata-fields' ) );
565 foreach ( $lines as $line ) {
567 if ( preg_match( '/^\\*\s*(.*?)\s*$/', $line, $matches ) ) {
568 $fields[] = $matches[1];
571 $fields = array_map( 'strtolower', $fields );
575 function formatMetadata( $image ) {
577 'visible' => array(),
578 'collapsed' => array()
580 $metadata = $image->getMetadata();
584 $exif = unserialize( $metadata );
588 unset( $exif['MEDIAWIKI_EXIF_VERSION'] );
589 $format = new FormatExif( $exif );
591 $formatted = $format->getFormattedData();
592 // Sort fields into visible and collapsed
593 $visibleFields = $this->visibleMetadataFields();
594 foreach ( $formatted as $name => $value ) {
595 $tag = strtolower( $name );
596 self
::addMeta( $result,
597 in_array( $tag, $visibleFields ) ?
'visible' : 'collapsed',