10 class BitmapHandler
extends ImageHandler
{
11 function normaliseParams( $image, &$params ) {
12 global $wgMaxImageArea;
13 if ( !parent
::normaliseParams( $image, $params ) ) {
17 $mimeType = $image->getMimeType();
18 $srcWidth = $image->getWidth( $params['page'] );
19 $srcHeight = $image->getHeight( $params['page'] );
21 # Don't make an image bigger than the source
22 $params['physicalWidth'] = $params['width'];
23 $params['physicalHeight'] = $params['height'];
25 if ( $params['physicalWidth'] >= $srcWidth ) {
26 $params['physicalWidth'] = $srcWidth;
27 $params['physicalHeight'] = $srcHeight;
28 # Skip scaling limit checks if no scaling is required
29 if( !$image->mustRender() )
33 # Don't thumbnail an image so big that it will fill hard drives and send servers into swap
34 # JPEG has the handy property of allowing thumbnailing without full decompression, so we make
35 # an exception for it.
36 if ( $mimeType !== 'image/jpeg' &&
37 $srcWidth * $srcHeight > $wgMaxImageArea )
46 // Function that returns the number of pixels to be thumbnailed.
47 // Intended for animated GIFs to multiply by the number of frames.
48 function getImageArea( $image, $width, $height ) {
49 return $width * $height;
52 function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
53 global $wgUseImageMagick, $wgImageMagickConvertCommand, $wgImageMagickTempDir;
54 global $wgCustomConvertCommand, $wgUseImageResize;
55 global $wgSharpenParameter, $wgSharpenReductionThreshold;
56 global $wgMaxAnimatedGifArea;
58 if ( !$this->normaliseParams( $image, $params ) ) {
59 return new TransformParameterError( $params );
61 $physicalWidth = $params['physicalWidth'];
62 $physicalHeight = $params['physicalHeight'];
63 $clientWidth = $params['width'];
64 $clientHeight = $params['height'];
65 $comment = isset( $params['descriptionUrl'] ) ?
"File source: ". $params['descriptionUrl'] : '';
66 $srcWidth = $image->getWidth();
67 $srcHeight = $image->getHeight();
68 $mimeType = $image->getMimeType();
69 $srcPath = $image->getPath();
71 wfDebug( __METHOD__
.": creating {$physicalWidth}x{$physicalHeight} thumbnail at $dstPath\n" );
73 if ( !$image->mustRender() && $physicalWidth == $srcWidth && $physicalHeight == $srcHeight ) {
74 # normaliseParams (or the user) wants us to return the unscaled image
75 wfDebug( __METHOD__
.": returning unscaled image\n" );
76 return new ThumbnailImage( $image, $image->getURL(), $clientWidth, $clientHeight, $srcPath );
80 // No output path available, client side scaling only
82 } elseif( !$wgUseImageResize ) {
84 } elseif ( $wgUseImageMagick ) {
86 } elseif ( $wgCustomConvertCommand ) {
88 } elseif ( function_exists( 'imagecreatetruecolor' ) ) {
93 wfDebug( __METHOD__
.": scaler $scaler\n" );
95 if ( $scaler == 'client' ) {
96 # Client-side image scaling, use the source URL
97 # Using the destination URL in a TRANSFORM_LATER request would be incorrect
98 return new ThumbnailImage( $image, $image->getURL(), $clientWidth, $clientHeight, $srcPath );
101 if ( $flags & self
::TRANSFORM_LATER
) {
102 wfDebug( __METHOD__
.": Transforming later per flags.\n" );
103 return new ThumbnailImage( $image, $dstUrl, $clientWidth, $clientHeight, $dstPath );
106 if ( !wfMkdirParents( dirname( $dstPath ) ) ) {
107 wfDebug( __METHOD__
.": Unable to create thumbnail destination directory, falling back to client scaling\n" );
108 return new ThumbnailImage( $image, $image->getURL(), $clientWidth, $clientHeight, $srcPath );
111 if ( $scaler == 'im' ) {
118 if ( $mimeType == 'image/jpeg' ) {
119 $quality = "-quality 80"; // 80%
120 # Sharpening, see bug 6193
121 if ( ( $physicalWidth +
$physicalHeight ) / ( $srcWidth +
$srcHeight ) < $wgSharpenReductionThreshold ) {
122 $sharpen = "-sharpen " . wfEscapeShellArg( $wgSharpenParameter );
124 } elseif ( $mimeType == 'image/png' ) {
125 $quality = "-quality 95"; // zlib 9, adaptive filtering
126 } elseif( $mimeType == 'image/gif' ) {
127 if( $this->getImageArea( $image, $srcWidth, $srcHeight ) > $wgMaxAnimatedGifArea ) {
128 // Extract initial frame only; we're so big it'll
129 // be a total drag. :P
132 // Coalesce is needed to scale animated GIFs properly (bug 1017).
133 $animation = ' -coalesce ';
137 if ( strval( $wgImageMagickTempDir ) !== '' ) {
138 $tempEnv = 'MAGICK_TMPDIR=' . wfEscapeShellArg( $wgImageMagickTempDir ) . ' ';
143 # Specify white background color, will be used for transparent images
144 # in Internet Explorer/Windows instead of default black.
146 # Note, we specify "-size {$physicalWidth}" and NOT "-size {$physicalWidth}x{$physicalHeight}".
147 # It seems that ImageMagick has a bug wherein it produces thumbnails of
148 # the wrong size in the second case.
152 wfEscapeShellArg( $wgImageMagickConvertCommand ) .
153 " {$quality} -background white -size {$physicalWidth} ".
154 wfEscapeShellArg( $this->escapeMagickInput( $srcPath, $scene ) ) .
156 // For the -resize option a "!" is needed to force exact size,
157 // or ImageMagick may decide your ratio is wrong and slice off
159 " -thumbnail " . wfEscapeShellArg( "{$physicalWidth}x{$physicalHeight}!" ) .
160 // Add the source url as a comment to the thumb.
161 " -set comment " . wfEscapeShellArg( $this->escapeMagickProperty( $comment ) ) .
162 " -depth 8 $sharpen " .
163 wfEscapeShellArg( $this->escapeMagickOutput( $dstPath ) ) . " 2>&1";
164 wfDebug( __METHOD__
.": running ImageMagick: $cmd\n" );
165 wfProfileIn( 'convert' );
166 $err = wfShellExec( $cmd, $retval );
167 wfProfileOut( 'convert' );
168 } elseif( $scaler == 'custom' ) {
169 # Use a custom convert command
170 # Variables: %s %d %w %h
171 $src = wfEscapeShellArg( $srcPath );
172 $dst = wfEscapeShellArg( $dstPath );
173 $cmd = $wgCustomConvertCommand;
174 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
175 $cmd = str_replace( '%h', $physicalHeight, str_replace( '%w', $physicalWidth, $cmd ) ); # Size
176 wfDebug( __METHOD__
.": Running custom convert command $cmd\n" );
177 wfProfileIn( 'convert' );
178 $err = wfShellExec( $cmd, $retval );
179 wfProfileOut( 'convert' );
180 } else /* $scaler == 'gd' */ {
181 # Use PHP's builtin GD library functions.
183 # First find out what kind of file this is, and select the correct
184 # input routine for this.
187 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
188 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( __CLASS__
, 'imageJpegWrapper' ) ),
189 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
190 'image/vnd.wap.wbmp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
191 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
193 if( !isset( $typemap[$mimeType] ) ) {
194 $err = 'Image type not supported';
196 $errMsg = wfMsg ( 'thumbnail_image-type' );
197 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $errMsg );
199 list( $loader, $colorStyle, $saveType ) = $typemap[$mimeType];
201 if( !function_exists( $loader ) ) {
202 $err = "Incomplete GD library configuration: missing function $loader";
204 $errMsg = wfMsg ( 'thumbnail_gd-library', $loader );
205 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $errMsg );
208 if ( !file_exists( $srcPath ) ) {
209 $err = "File seems to be missing: $srcPath";
211 $errMsg = wfMsg ( 'thumbnail_image-missing', $srcPath );
212 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $errMsg );
215 $src_image = call_user_func( $loader, $srcPath );
216 $dst_image = imagecreatetruecolor( $physicalWidth, $physicalHeight );
218 // Initialise the destination image to transparent instead of
219 // the default solid black, to support PNG and GIF transparency nicely
220 $background = imagecolorallocate( $dst_image, 0, 0, 0 );
221 imagecolortransparent( $dst_image, $background );
222 imagealphablending( $dst_image, false );
224 if( $colorStyle == 'palette' ) {
225 // Don't resample for paletted GIF images.
226 // It may just uglify them, and completely breaks transparency.
227 imagecopyresized( $dst_image, $src_image,
229 $physicalWidth, $physicalHeight, imagesx( $src_image ), imagesy( $src_image ) );
231 imagecopyresampled( $dst_image, $src_image,
233 $physicalWidth, $physicalHeight, imagesx( $src_image ), imagesy( $src_image ) );
236 imagesavealpha( $dst_image, true );
238 call_user_func( $saveType, $dst_image, $dstPath );
239 imagedestroy( $dst_image );
240 imagedestroy( $src_image );
244 $removed = $this->removeBadFile( $dstPath, $retval );
245 if ( $retval != 0 ||
$removed ) {
246 wfDebugLog( 'thumbnail',
247 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
248 wfHostname(), $retval, trim($err), $cmd ) );
249 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $err );
251 return new ThumbnailImage( $image, $dstUrl, $clientWidth, $clientHeight, $dstPath );
256 * Escape a string for ImageMagick's property input (e.g. -set -comment)
257 * See InterpretImageProperties() in magick/property.c
259 function escapeMagickProperty( $s ) {
260 // Double the backslashes
261 $s = str_replace( '\\', '\\\\', $s );
262 // Double the percents
263 $s = str_replace( '%', '%%', $s );
264 // Escape initial - or @
265 if ( strlen( $s ) > 0 && ( $s[0] === '-' ||
$s[0] === '@' ) ) {
272 * Escape a string for ImageMagick's input filenames. See ExpandFilenames()
273 * and GetPathComponent() in magick/utility.c.
275 * This won't work with an initial ~ or @, so input files should be prefixed
276 * with the directory name.
278 * Glob character unescaping is broken in ImageMagick before 6.6.1-5, but
279 * it's broken in a way that doesn't involve trying to convert every file
280 * in a directory, so we're better off escaping and waiting for the bugfix
281 * to filter down to users.
283 * @param $path string The file path
284 * @param $scene string The scene specification, or false if there is none
286 function escapeMagickInput( $path, $scene = false ) {
287 # Die on initial metacharacters (caller should prepend path)
288 $firstChar = substr( $path, 0, 1 );
289 if ( $firstChar === '~' ||
$firstChar === '@' ) {
290 throw new MWException( __METHOD__
.': cannot escape this path name' );
294 $path = preg_replace( '/[*?\[\]{}]/', '\\\\\0', $path );
296 return $this->escapeMagickPath( $path, $scene );
300 * Escape a string for ImageMagick's output filename. See
301 * InterpretImageFilename() in magick/image.c.
303 function escapeMagickOutput( $path, $scene = false ) {
304 $path = str_replace( '%', '%%', $path );
305 return $this->escapeMagickPath( $path, $scene );
309 * Armour a string against ImageMagick's GetPathComponent(). This is a
310 * helper function for escapeMagickInput() and escapeMagickOutput().
312 * @param $path string The file path
313 * @param $scene string The scene specification, or false if there is none
315 protected function escapeMagickPath( $path, $scene = false ) {
316 # Die on format specifiers (other than drive letters). The regex is
317 # meant to match all the formats you get from "convert -list format"
318 if ( preg_match( '/^([a-zA-Z0-9-]+):/', $path, $m ) ) {
319 if ( wfIsWindows() && is_dir( $m[0] ) ) {
320 // OK, it's a drive letter
321 // ImageMagick has a similar exception, see IsMagickConflict()
323 throw new MWException( __METHOD__
.': unexpected colon character in path name' );
327 # If there are square brackets, add a do-nothing scene specification
328 # to force a literal interpretation
329 if ( $scene === false ) {
330 if ( strpos( $path, '[' ) !== false ) {
339 static function imageJpegWrapper( $dst_image, $thumbPath ) {
340 imageinterlace( $dst_image );
341 imagejpeg( $dst_image, $thumbPath, 95 );
345 function getMetadata( $image, $filename ) {
347 if( $wgShowEXIF && file_exists( $filename ) ) {
348 $exif = new Exif( $filename );
349 $data = $exif->getFilteredData();
351 $data['MEDIAWIKI_EXIF_VERSION'] = Exif
::version();
352 return serialize( $data );
361 function getMetadataType( $image ) {
365 function isMetadataValid( $image, $metadata ) {
367 if ( !$wgShowEXIF ) {
368 # Metadata disabled and so an empty field is expected
371 if ( $metadata === '0' ) {
372 # Special value indicating that there is no EXIF data in the file
375 $exif = @unserialize
( $metadata );
376 if ( !isset( $exif['MEDIAWIKI_EXIF_VERSION'] ) ||
377 $exif['MEDIAWIKI_EXIF_VERSION'] != Exif
::version() )
380 wfDebug( __METHOD__
.": wrong version\n" );
387 * Get a list of EXIF metadata items which should be displayed when
388 * the metadata table is collapsed.
390 * @return array of strings
393 function visibleMetadataFields() {
395 $lines = explode( "\n", wfMsgForContent( 'metadata-fields' ) );
396 foreach( $lines as $line ) {
398 if( preg_match( '/^\\*\s*(.*?)\s*$/', $line, $matches ) ) {
399 $fields[] = $matches[1];
402 $fields = array_map( 'strtolower', $fields );
406 function formatMetadata( $image ) {
408 'visible' => array(),
409 'collapsed' => array()
411 $metadata = $image->getMetadata();
415 $exif = unserialize( $metadata );
419 unset( $exif['MEDIAWIKI_EXIF_VERSION'] );
420 $format = new FormatExif( $exif );
422 $formatted = $format->getFormattedData();
423 // Sort fields into visible and collapsed
424 $visibleFields = $this->visibleMetadataFields();
425 foreach ( $formatted as $name => $value ) {
426 $tag = strtolower( $name );
427 self
::addMeta( $result,
428 in_array( $tag, $visibleFields ) ?
'visible' : 'collapsed',