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 = '';
124 if ( $mimeType == 'image/jpeg' ) {
125 $quality = "-quality 80"; // 80%
126 # Sharpening, see bug 6193
127 if ( ( $physicalWidth +
$physicalHeight ) / ( $srcWidth +
$srcHeight ) < $wgSharpenReductionThreshold ) {
128 $sharpen = "-sharpen " . wfEscapeShellArg( $wgSharpenParameter );
130 // JPEG decoder hint to reduce memory, available since IM 6.5.6-2
131 $decoderHint = "-define jpeg:size={$physicalWidth}x{$physicalHeight}";
132 } elseif ( $mimeType == 'image/png' ) {
133 $quality = "-quality 95"; // zlib 9, adaptive filtering
134 } elseif( $mimeType == 'image/gif' ) {
135 if( $this->getImageArea( $image, $srcWidth, $srcHeight ) > $wgMaxAnimatedGifArea ) {
136 // Extract initial frame only; we're so big it'll
137 // be a total drag. :P
139 } elseif( $this->isAnimatedImage( $image ) ) {
140 // Coalesce is needed to scale animated GIFs properly (bug 1017).
141 $animation_pre = '-coalesce';
142 // We optimize the output, but -optimize is broken,
143 // use optimizeTransparency instead (bug 11822)
144 if( version_compare( $this->getMagickVersion(), "6.3.5" ) >= 0 ) {
145 $animation_post = '-fuzz 5% -layers optimizeTransparency +map';
150 if ( strval( $wgImageMagickTempDir ) !== '' ) {
151 $tempEnv = 'MAGICK_TMPDIR=' . wfEscapeShellArg( $wgImageMagickTempDir ) . ' ';
158 // Use one thread only, to avoid deadlock bugs on OOM
159 'OMP_NUM_THREADS=1 ' .
160 wfEscapeShellArg( $wgImageMagickConvertCommand ) .
161 // Specify white background color, will be used for transparent images
162 // in Internet Explorer/Windows instead of default black.
163 " {$quality} -background white".
165 wfEscapeShellArg( $this->escapeMagickInput( $srcPath, $scene ) ) .
166 " {$animation_pre}" .
167 // For the -thumbnail option a "!" is needed to force exact size,
168 // or ImageMagick may decide your ratio is wrong and slice off
170 " -thumbnail " . wfEscapeShellArg( "{$physicalWidth}x{$physicalHeight}!" ) .
171 // Add the source url as a comment to the thumb.
172 " -set comment " . wfEscapeShellArg( $this->escapeMagickProperty( $comment ) ) .
173 " -depth 8 $sharpen" .
174 " {$animation_post} " .
175 wfEscapeShellArg( $this->escapeMagickOutput( $dstPath ) ) . " 2>&1";
176 wfDebug( __METHOD__
.": running ImageMagick: $cmd\n" );
177 wfProfileIn( 'convert' );
178 $err = wfShellExec( $cmd, $retval );
179 wfProfileOut( 'convert' );
180 } elseif( $scaler == 'custom' ) {
181 # Use a custom convert command
182 # Variables: %s %d %w %h
183 $src = wfEscapeShellArg( $srcPath );
184 $dst = wfEscapeShellArg( $dstPath );
185 $cmd = $wgCustomConvertCommand;
186 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
187 $cmd = str_replace( '%h', $physicalHeight, str_replace( '%w', $physicalWidth, $cmd ) ); # Size
188 wfDebug( __METHOD__
.": Running custom convert command $cmd\n" );
189 wfProfileIn( 'convert' );
190 $err = wfShellExec( $cmd, $retval );
191 wfProfileOut( 'convert' );
192 } else /* $scaler == 'gd' */ {
193 # Use PHP's builtin GD library functions.
195 # First find out what kind of file this is, and select the correct
196 # input routine for this.
199 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
200 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( __CLASS__
, 'imageJpegWrapper' ) ),
201 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
202 'image/vnd.wap.wbmp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
203 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
205 if( !isset( $typemap[$mimeType] ) ) {
206 $err = 'Image type not supported';
208 $errMsg = wfMsg ( 'thumbnail_image-type' );
209 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $errMsg );
211 list( $loader, $colorStyle, $saveType ) = $typemap[$mimeType];
213 if( !function_exists( $loader ) ) {
214 $err = "Incomplete GD library configuration: missing function $loader";
216 $errMsg = wfMsg ( 'thumbnail_gd-library', $loader );
217 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $errMsg );
220 if ( !file_exists( $srcPath ) ) {
221 $err = "File seems to be missing: $srcPath";
223 $errMsg = wfMsg ( 'thumbnail_image-missing', $srcPath );
224 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $errMsg );
227 $src_image = call_user_func( $loader, $srcPath );
228 $dst_image = imagecreatetruecolor( $physicalWidth, $physicalHeight );
230 // Initialise the destination image to transparent instead of
231 // the default solid black, to support PNG and GIF transparency nicely
232 $background = imagecolorallocate( $dst_image, 0, 0, 0 );
233 imagecolortransparent( $dst_image, $background );
234 imagealphablending( $dst_image, false );
236 if( $colorStyle == 'palette' ) {
237 // Don't resample for paletted GIF images.
238 // It may just uglify them, and completely breaks transparency.
239 imagecopyresized( $dst_image, $src_image,
241 $physicalWidth, $physicalHeight, imagesx( $src_image ), imagesy( $src_image ) );
243 imagecopyresampled( $dst_image, $src_image,
245 $physicalWidth, $physicalHeight, imagesx( $src_image ), imagesy( $src_image ) );
248 imagesavealpha( $dst_image, true );
250 call_user_func( $saveType, $dst_image, $dstPath );
251 imagedestroy( $dst_image );
252 imagedestroy( $src_image );
256 $removed = $this->removeBadFile( $dstPath, $retval );
257 if ( $retval != 0 ||
$removed ) {
258 wfDebugLog( 'thumbnail',
259 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
260 wfHostname(), $retval, trim($err), $cmd ) );
261 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $err );
263 return new ThumbnailImage( $image, $dstUrl, $clientWidth, $clientHeight, $dstPath );
268 * Escape a string for ImageMagick's property input (e.g. -set -comment)
269 * See InterpretImageProperties() in magick/property.c
271 function escapeMagickProperty( $s ) {
272 // Double the backslashes
273 $s = str_replace( '\\', '\\\\', $s );
274 // Double the percents
275 $s = str_replace( '%', '%%', $s );
276 // Escape initial - or @
277 if ( strlen( $s ) > 0 && ( $s[0] === '-' ||
$s[0] === '@' ) ) {
284 * Escape a string for ImageMagick's input filenames. See ExpandFilenames()
285 * and GetPathComponent() in magick/utility.c.
287 * This won't work with an initial ~ or @, so input files should be prefixed
288 * with the directory name.
290 * Glob character unescaping is broken in ImageMagick before 6.6.1-5, but
291 * it's broken in a way that doesn't involve trying to convert every file
292 * in a directory, so we're better off escaping and waiting for the bugfix
293 * to filter down to users.
295 * @param $path string The file path
296 * @param $scene string The scene specification, or false if there is none
298 function escapeMagickInput( $path, $scene = false ) {
299 # Die on initial metacharacters (caller should prepend path)
300 $firstChar = substr( $path, 0, 1 );
301 if ( $firstChar === '~' ||
$firstChar === '@' ) {
302 throw new MWException( __METHOD__
.': cannot escape this path name' );
306 $path = preg_replace( '/[*?\[\]{}]/', '\\\\\0', $path );
308 return $this->escapeMagickPath( $path, $scene );
312 * Escape a string for ImageMagick's output filename. See
313 * InterpretImageFilename() in magick/image.c.
315 function escapeMagickOutput( $path, $scene = false ) {
316 $path = str_replace( '%', '%%', $path );
317 return $this->escapeMagickPath( $path, $scene );
321 * Armour a string against ImageMagick's GetPathComponent(). This is a
322 * helper function for escapeMagickInput() and escapeMagickOutput().
324 * @param $path string The file path
325 * @param $scene string The scene specification, or false if there is none
327 protected function escapeMagickPath( $path, $scene = false ) {
328 # Die on format specifiers (other than drive letters). The regex is
329 # meant to match all the formats you get from "convert -list format"
330 if ( preg_match( '/^([a-zA-Z0-9-]+):/', $path, $m ) ) {
331 if ( wfIsWindows() && is_dir( $m[0] ) ) {
332 // OK, it's a drive letter
333 // ImageMagick has a similar exception, see IsMagickConflict()
335 throw new MWException( __METHOD__
.': unexpected colon character in path name' );
339 # If there are square brackets, add a do-nothing scene specification
340 # to force a literal interpretation
341 if ( $scene === false ) {
342 if ( strpos( $path, '[' ) !== false ) {
352 * Retrieve the version of the installed ImageMagick
353 * You can use PHPs version_compare() to use this value
354 * Value is cached for one hour.
355 * @return String representing the IM version.
357 protected function getMagickVersion() {
360 $cache = $wgMemc->get( "imagemagick-version" );
362 global $wgImageMagickConvertCommand;
363 $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . ' -version';
364 wfDebug( __METHOD__
.": Running convert -version\n" );
366 $return = wfShellExec( $cmd, $retval );
367 $x = preg_match('/Version: ImageMagick ([0-9]*\.[0-9]*\.[0-9]*)/', $return, $matches);
369 wfDebug( __METHOD__
.": ImageMagick version check failed\n" );
372 $wgMemc->set( "imagemagick-version", $matches[1], 3600 );
378 static function imageJpegWrapper( $dst_image, $thumbPath ) {
379 imageinterlace( $dst_image );
380 imagejpeg( $dst_image, $thumbPath, 95 );
384 function getMetadata( $image, $filename ) {
386 if( $wgShowEXIF && file_exists( $filename ) ) {
387 $exif = new Exif( $filename );
388 $data = $exif->getFilteredData();
390 $data['MEDIAWIKI_EXIF_VERSION'] = Exif
::version();
391 return serialize( $data );
400 function getMetadataType( $image ) {
404 function isMetadataValid( $image, $metadata ) {
406 if ( !$wgShowEXIF ) {
407 # Metadata disabled and so an empty field is expected
410 if ( $metadata === '0' ) {
411 # Special value indicating that there is no EXIF data in the file
414 wfSuppressWarnings();
415 $exif = unserialize( $metadata );
417 if ( !isset( $exif['MEDIAWIKI_EXIF_VERSION'] ) ||
418 $exif['MEDIAWIKI_EXIF_VERSION'] != Exif
::version() )
421 wfDebug( __METHOD__
.": wrong version\n" );
428 * Get a list of EXIF metadata items which should be displayed when
429 * the metadata table is collapsed.
431 * @return array of strings
434 function visibleMetadataFields() {
436 $lines = explode( "\n", wfMsgForContent( 'metadata-fields' ) );
437 foreach( $lines as $line ) {
439 if( preg_match( '/^\\*\s*(.*?)\s*$/', $line, $matches ) ) {
440 $fields[] = $matches[1];
443 $fields = array_map( 'strtolower', $fields );
447 function formatMetadata( $image ) {
449 'visible' => array(),
450 'collapsed' => array()
452 $metadata = $image->getMetadata();
456 $exif = unserialize( $metadata );
460 unset( $exif['MEDIAWIKI_EXIF_VERSION'] );
461 $format = new FormatExif( $exif );
463 $formatted = $format->getFormattedData();
464 // Sort fields into visible and collapsed
465 $visibleFields = $this->visibleMetadataFields();
466 foreach ( $formatted as $name => $value ) {
467 $tag = strtolower( $name );
468 self
::addMeta( $result,
469 in_array( $tag, $visibleFields ) ?
'visible' : 'collapsed',