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 if ( $mimeType !== 'image/jpeg' &&
41 $srcWidth * $srcHeight > $wgMaxImageArea )
50 // Function that returns the number of pixels to be thumbnailed.
51 // Intended for animated GIFs to multiply by the number of frames.
52 function getImageArea( $image, $width, $height ) {
53 return $width * $height;
56 function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
57 global $wgUseImageMagick, $wgImageMagickConvertCommand, $wgImageMagickTempDir;
58 global $wgCustomConvertCommand, $wgUseImageResize;
59 global $wgSharpenParameter, $wgSharpenReductionThreshold;
60 global $wgMaxAnimatedGifArea;
62 if ( !$this->normaliseParams( $image, $params ) ) {
63 return new TransformParameterError( $params );
65 $physicalWidth = $params['physicalWidth'];
66 $physicalHeight = $params['physicalHeight'];
67 $clientWidth = $params['width'];
68 $clientHeight = $params['height'];
69 $comment = isset( $params['descriptionUrl'] ) ?
"File source: ". $params['descriptionUrl'] : '';
70 $srcWidth = $image->getWidth();
71 $srcHeight = $image->getHeight();
72 $mimeType = $image->getMimeType();
73 $srcPath = $image->getPath();
75 wfDebug( __METHOD__
.": creating {$physicalWidth}x{$physicalHeight} thumbnail at $dstPath\n" );
77 if ( !$image->mustRender() && $physicalWidth == $srcWidth && $physicalHeight == $srcHeight ) {
78 # normaliseParams (or the user) wants us to return the unscaled image
79 wfDebug( __METHOD__
.": returning unscaled image\n" );
80 return new ThumbnailImage( $image, $image->getURL(), $clientWidth, $clientHeight, $srcPath );
84 // No output path available, client side scaling only
86 } elseif( !$wgUseImageResize ) {
88 } elseif ( $wgUseImageMagick ) {
90 } elseif ( $wgCustomConvertCommand ) {
92 } elseif ( function_exists( 'imagecreatetruecolor' ) ) {
97 wfDebug( __METHOD__
.": scaler $scaler\n" );
99 if ( $scaler == 'client' ) {
100 # Client-side image scaling, use the source URL
101 # Using the destination URL in a TRANSFORM_LATER request would be incorrect
102 return new ThumbnailImage( $image, $image->getURL(), $clientWidth, $clientHeight, $srcPath );
105 if ( $flags & self
::TRANSFORM_LATER
) {
106 wfDebug( __METHOD__
.": Transforming later per flags.\n" );
107 return new ThumbnailImage( $image, $dstUrl, $clientWidth, $clientHeight, $dstPath );
110 if ( !wfMkdirParents( dirname( $dstPath ) ) ) {
111 wfDebug( __METHOD__
.": Unable to create thumbnail destination directory, falling back to client scaling\n" );
112 return new ThumbnailImage( $image, $image->getURL(), $clientWidth, $clientHeight, $srcPath );
115 if ( $scaler == 'im' ) {
122 $animation_post = '';
123 if ( $mimeType == 'image/jpeg' ) {
124 $quality = "-quality 80"; // 80%
125 # Sharpening, see bug 6193
126 if ( ( $physicalWidth +
$physicalHeight ) / ( $srcWidth +
$srcHeight ) < $wgSharpenReductionThreshold ) {
127 $sharpen = "-sharpen " . wfEscapeShellArg( $wgSharpenParameter );
129 } elseif ( $mimeType == 'image/png' ) {
130 $quality = "-quality 95"; // zlib 9, adaptive filtering
131 } elseif( $mimeType == 'image/gif' ) {
132 if( $this->getImageArea( $image, $srcWidth, $srcHeight ) > $wgMaxAnimatedGifArea ) {
133 // Extract initial frame only; we're so big it'll
134 // be a total drag. :P
136 } elseif( $this->isAnimatedImage( $image ) ) {
137 // Coalesce is needed to scale animated GIFs properly (bug 1017).
138 $animation_pre = '-coalesce';
139 // We optimize the output, but -optimize is broken,
140 // use optimizeTransparency instead (bug 11822)
141 if( version_compare( $this->getMagickVersion(), "6.3.5" ) >= 0 ) {
142 $animation_post = '-fuzz 5% -layers optimizeTransparency +map';
147 if ( strval( $wgImageMagickTempDir ) !== '' ) {
148 $tempEnv = 'MAGICK_TMPDIR=' . wfEscapeShellArg( $wgImageMagickTempDir ) . ' ';
153 # Specify white background color, will be used for transparent images
154 # in Internet Explorer/Windows instead of default black.
156 # Note, we specify "-size {$physicalWidth}" and NOT "-size {$physicalWidth}x{$physicalHeight}".
157 # It seems that ImageMagick has a bug wherein it produces thumbnails of
158 # the wrong size in the second case.
162 wfEscapeShellArg( $wgImageMagickConvertCommand ) .
163 " {$quality} -background white -size {$physicalWidth} ".
164 wfEscapeShellArg( $this->escapeMagickInput( $srcPath, $scene ) ) .
165 " {$animation_pre}" .
166 // For the -resize option a "!" is needed to force exact size,
167 // or ImageMagick may decide your ratio is wrong and slice off
169 " -thumbnail " . wfEscapeShellArg( "{$physicalWidth}x{$physicalHeight}!" ) .
170 // Add the source url as a comment to the thumb.
171 " -set comment " . wfEscapeShellArg( $this->escapeMagickProperty( $comment ) ) .
172 " -depth 8 $sharpen" .
173 " {$animation_post} " .
174 wfEscapeShellArg( $this->escapeMagickOutput( $dstPath ) ) . " 2>&1";
175 wfDebug( __METHOD__
.": running ImageMagick: $cmd\n" );
176 wfProfileIn( 'convert' );
177 $err = wfShellExec( $cmd, $retval );
178 wfProfileOut( 'convert' );
179 } elseif( $scaler == 'custom' ) {
180 # Use a custom convert command
181 # Variables: %s %d %w %h
182 $src = wfEscapeShellArg( $srcPath );
183 $dst = wfEscapeShellArg( $dstPath );
184 $cmd = $wgCustomConvertCommand;
185 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
186 $cmd = str_replace( '%h', $physicalHeight, str_replace( '%w', $physicalWidth, $cmd ) ); # Size
187 wfDebug( __METHOD__
.": Running custom convert command $cmd\n" );
188 wfProfileIn( 'convert' );
189 $err = wfShellExec( $cmd, $retval );
190 wfProfileOut( 'convert' );
191 } else /* $scaler == 'gd' */ {
192 # Use PHP's builtin GD library functions.
194 # First find out what kind of file this is, and select the correct
195 # input routine for this.
198 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
199 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( __CLASS__
, 'imageJpegWrapper' ) ),
200 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
201 'image/vnd.wap.wbmp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
202 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
204 if( !isset( $typemap[$mimeType] ) ) {
205 $err = 'Image type not supported';
207 $errMsg = wfMsg ( 'thumbnail_image-type' );
208 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $errMsg );
210 list( $loader, $colorStyle, $saveType ) = $typemap[$mimeType];
212 if( !function_exists( $loader ) ) {
213 $err = "Incomplete GD library configuration: missing function $loader";
215 $errMsg = wfMsg ( 'thumbnail_gd-library', $loader );
216 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $errMsg );
219 if ( !file_exists( $srcPath ) ) {
220 $err = "File seems to be missing: $srcPath";
222 $errMsg = wfMsg ( 'thumbnail_image-missing', $srcPath );
223 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $errMsg );
226 $src_image = call_user_func( $loader, $srcPath );
227 $dst_image = imagecreatetruecolor( $physicalWidth, $physicalHeight );
229 // Initialise the destination image to transparent instead of
230 // the default solid black, to support PNG and GIF transparency nicely
231 $background = imagecolorallocate( $dst_image, 0, 0, 0 );
232 imagecolortransparent( $dst_image, $background );
233 imagealphablending( $dst_image, false );
235 if( $colorStyle == 'palette' ) {
236 // Don't resample for paletted GIF images.
237 // It may just uglify them, and completely breaks transparency.
238 imagecopyresized( $dst_image, $src_image,
240 $physicalWidth, $physicalHeight, imagesx( $src_image ), imagesy( $src_image ) );
242 imagecopyresampled( $dst_image, $src_image,
244 $physicalWidth, $physicalHeight, imagesx( $src_image ), imagesy( $src_image ) );
247 imagesavealpha( $dst_image, true );
249 call_user_func( $saveType, $dst_image, $dstPath );
250 imagedestroy( $dst_image );
251 imagedestroy( $src_image );
255 $removed = $this->removeBadFile( $dstPath, $retval );
256 if ( $retval != 0 ||
$removed ) {
257 wfDebugLog( 'thumbnail',
258 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
259 wfHostname(), $retval, trim($err), $cmd ) );
260 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $err );
262 return new ThumbnailImage( $image, $dstUrl, $clientWidth, $clientHeight, $dstPath );
267 * Escape a string for ImageMagick's property input (e.g. -set -comment)
268 * See InterpretImageProperties() in magick/property.c
270 function escapeMagickProperty( $s ) {
271 // Double the backslashes
272 $s = str_replace( '\\', '\\\\', $s );
273 // Double the percents
274 $s = str_replace( '%', '%%', $s );
275 // Escape initial - or @
276 if ( strlen( $s ) > 0 && ( $s[0] === '-' ||
$s[0] === '@' ) ) {
283 * Escape a string for ImageMagick's input filenames. See ExpandFilenames()
284 * and GetPathComponent() in magick/utility.c.
286 * This won't work with an initial ~ or @, so input files should be prefixed
287 * with the directory name.
289 * Glob character unescaping is broken in ImageMagick before 6.6.1-5, but
290 * it's broken in a way that doesn't involve trying to convert every file
291 * in a directory, so we're better off escaping and waiting for the bugfix
292 * to filter down to users.
294 * @param $path string The file path
295 * @param $scene string The scene specification, or false if there is none
297 function escapeMagickInput( $path, $scene = false ) {
298 # Die on initial metacharacters (caller should prepend path)
299 $firstChar = substr( $path, 0, 1 );
300 if ( $firstChar === '~' ||
$firstChar === '@' ) {
301 throw new MWException( __METHOD__
.': cannot escape this path name' );
305 $path = preg_replace( '/[*?\[\]{}]/', '\\\\\0', $path );
307 return $this->escapeMagickPath( $path, $scene );
311 * Escape a string for ImageMagick's output filename. See
312 * InterpretImageFilename() in magick/image.c.
314 function escapeMagickOutput( $path, $scene = false ) {
315 $path = str_replace( '%', '%%', $path );
316 return $this->escapeMagickPath( $path, $scene );
320 * Armour a string against ImageMagick's GetPathComponent(). This is a
321 * helper function for escapeMagickInput() and escapeMagickOutput().
323 * @param $path string The file path
324 * @param $scene string The scene specification, or false if there is none
326 protected function escapeMagickPath( $path, $scene = false ) {
327 # Die on format specifiers (other than drive letters). The regex is
328 # meant to match all the formats you get from "convert -list format"
329 if ( preg_match( '/^([a-zA-Z0-9-]+):/', $path, $m ) ) {
330 if ( wfIsWindows() && is_dir( $m[0] ) ) {
331 // OK, it's a drive letter
332 // ImageMagick has a similar exception, see IsMagickConflict()
334 throw new MWException( __METHOD__
.': unexpected colon character in path name' );
338 # If there are square brackets, add a do-nothing scene specification
339 # to force a literal interpretation
340 if ( $scene === false ) {
341 if ( strpos( $path, '[' ) !== false ) {
351 * Retrieve the version of the installed ImageMagick
352 * You can use PHPs version_compare() to use this value
353 * Value is cached for one hour.
354 * @return String representing the IM version.
356 protected function getMagickVersion() {
359 $cache = $wgMemc->get( "imagemagick-version" );
361 global $wgImageMagickConvertCommand;
362 $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . ' -version';
363 wfDebug( __METHOD__
.": Running convert -version\n" );
364 $return = wfShellExec( $cmd, $retval );
365 $x = preg_match('/Version: ImageMagick ([0-9]*\.[0-9]*\.[0-9]*)/', $return, $matches);
367 wfDebug( __METHOD__
.": ImageMagick version check failed\n" );
370 $wgMemc->set( "imagemagick-version", $matches[1], 3600 );
376 static function imageJpegWrapper( $dst_image, $thumbPath ) {
377 imageinterlace( $dst_image );
378 imagejpeg( $dst_image, $thumbPath, 95 );
382 function getMetadata( $image, $filename ) {
384 if( $wgShowEXIF && file_exists( $filename ) ) {
385 $exif = new Exif( $filename );
386 $data = $exif->getFilteredData();
388 $data['MEDIAWIKI_EXIF_VERSION'] = Exif
::version();
389 return serialize( $data );
398 function getMetadataType( $image ) {
402 function isMetadataValid( $image, $metadata ) {
404 if ( !$wgShowEXIF ) {
405 # Metadata disabled and so an empty field is expected
408 if ( $metadata === '0' ) {
409 # Special value indicating that there is no EXIF data in the file
412 wfSuppressWarnings();
413 $exif = unserialize( $metadata );
415 if ( !isset( $exif['MEDIAWIKI_EXIF_VERSION'] ) ||
416 $exif['MEDIAWIKI_EXIF_VERSION'] != Exif
::version() )
419 wfDebug( __METHOD__
.": wrong version\n" );
426 * Get a list of EXIF metadata items which should be displayed when
427 * the metadata table is collapsed.
429 * @return array of strings
432 function visibleMetadataFields() {
434 $lines = explode( "\n", wfMsgForContent( 'metadata-fields' ) );
435 foreach( $lines as $line ) {
437 if( preg_match( '/^\\*\s*(.*?)\s*$/', $line, $matches ) ) {
438 $fields[] = $matches[1];
441 $fields = array_map( 'strtolower', $fields );
445 function formatMetadata( $image ) {
447 'visible' => array(),
448 'collapsed' => array()
450 $metadata = $image->getMetadata();
454 $exif = unserialize( $metadata );
458 unset( $exif['MEDIAWIKI_EXIF_VERSION'] );
459 $format = new FormatExif( $exif );
461 $formatted = $format->getFormattedData();
462 // Sort fields into visible and collapsed
463 $visibleFields = $this->visibleMetadataFields();
464 foreach ( $formatted as $name => $value ) {
465 $tag = strtolower( $name );
466 self
::addMeta( $result,
467 in_array( $tag, $visibleFields ) ?
'visible' : 'collapsed',