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 thumbnail an image so big that it will fill hard drives and send servers into swap
22 # JPEG has the handy property of allowing thumbnailing without full decompression, so we make
23 # an exception for it.
24 if ( $mimeType !== 'image/jpeg' &&
25 $this->getImageArea( $image, $srcWidth, $srcHeight ) > $wgMaxImageArea )
30 # Don't make an image bigger than the source
31 $params['physicalWidth'] = $params['width'];
32 $params['physicalHeight'] = $params['height'];
34 if ( $params['physicalWidth'] >= $srcWidth ) {
35 $params['physicalWidth'] = $srcWidth;
36 $params['physicalHeight'] = $srcHeight;
44 // Function that returns the number of pixels to be thumbnailed.
45 // Intended for animated GIFs to multiply by the number of frames.
46 function getImageArea( $image, $width, $height ) {
47 return $width * $height;
50 function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
51 global $wgUseImageMagick, $wgImageMagickConvertCommand, $wgImageMagickTempDir;
52 global $wgCustomConvertCommand, $wgUseImageResize;
53 global $wgSharpenParameter, $wgSharpenReductionThreshold;
54 global $wgMaxAnimatedGifArea;
56 if ( !$this->normaliseParams( $image, $params ) ) {
57 return new TransformParameterError( $params );
59 $physicalWidth = $params['physicalWidth'];
60 $physicalHeight = $params['physicalHeight'];
61 $clientWidth = $params['width'];
62 $clientHeight = $params['height'];
63 $comment = isset( $params['descriptionUrl'] ) ? "File source: ". $params['descriptionUrl'] : '';
64 $srcWidth = $image->getWidth();
65 $srcHeight = $image->getHeight();
66 $mimeType = $image->getMimeType();
67 $srcPath = $image->getPath();
69 wfDebug( __METHOD__.": creating {$physicalWidth}x{$physicalHeight} thumbnail at $dstPath\n" );
71 if ( !$image->mustRender() && $physicalWidth == $srcWidth && $physicalHeight == $srcHeight ) {
72 # normaliseParams (or the user) wants us to return the unscaled image
73 wfDebug( __METHOD__.": returning unscaled image\n" );
74 return new ThumbnailImage( $image, $image->getURL(), $clientWidth, $clientHeight, $srcPath );
78 // No output path available, client side scaling only
80 } elseif( !$wgUseImageResize ) {
82 } elseif ( $wgUseImageMagick ) {
84 } elseif ( $wgCustomConvertCommand ) {
86 } elseif ( function_exists( 'imagecreatetruecolor' ) ) {
91 wfDebug( __METHOD__.": scaler $scaler\n" );
93 if ( $scaler == 'client' ) {
94 # Client-side image scaling, use the source URL
95 # Using the destination URL in a TRANSFORM_LATER request would be incorrect
96 return new ThumbnailImage( $image, $image->getURL(), $clientWidth, $clientHeight, $srcPath );
99 if ( $flags & self::TRANSFORM_LATER ) {
100 wfDebug( __METHOD__.": Transforming later per flags.\n" );
101 return new ThumbnailImage( $image, $dstUrl, $clientWidth, $clientHeight, $dstPath );
104 if ( !wfMkdirParents( dirname( $dstPath ) ) ) {
105 wfDebug( __METHOD__.": Unable to create thumbnail destination directory, falling back to client scaling\n" );
106 return new ThumbnailImage( $image, $image->getURL(), $clientWidth, $clientHeight, $srcPath );
109 if ( $scaler == 'im' ) {
116 if ( $mimeType == 'image/jpeg' ) {
117 $quality = "-quality 80"; // 80%
118 # Sharpening, see bug 6193
119 if ( ( $physicalWidth + $physicalHeight ) / ( $srcWidth + $srcHeight ) < $wgSharpenReductionThreshold ) {
120 $sharpen = "-sharpen " . wfEscapeShellArg( $wgSharpenParameter );
122 } elseif ( $mimeType == 'image/png' ) {
123 $quality = "-quality 95"; // zlib 9, adaptive filtering
124 } elseif( $mimeType == 'image/gif' ) {
125 if( $srcWidth * $srcHeight > $wgMaxAnimatedGifArea ) {
126 // Extract initial frame only; we're so big it'll
127 // be a total drag. :P
130 // Coalesce is needed to scale animated GIFs properly (bug 1017).
131 $animation = ' -coalesce ';
135 if ( strval( $wgImageMagickTempDir ) !== '' ) {
136 $tempEnv = 'MAGICK_TMPDIR=' . wfEscapeShellArg( $wgImageMagickTempDir ) . ' ';
141 # Specify white background color, will be used for transparent images
142 # in Internet Explorer/Windows instead of default black.
144 # Note, we specify "-size {$physicalWidth}" and NOT "-size {$physicalWidth}x{$physicalHeight}".
145 # It seems that ImageMagick has a bug wherein it produces thumbnails of
146 # the wrong size in the second case.
150 wfEscapeShellArg( $wgImageMagickConvertCommand ) .
151 " {$quality} -background white -size {$physicalWidth} ".
152 wfEscapeShellArg( $this->escapeMagickInput( $srcPath, $scene ) ) .
154 // For the -resize option a "!" is needed to force exact size,
155 // or ImageMagick may decide your ratio is wrong and slice off
157 " -thumbnail " . wfEscapeShellArg( "{$physicalWidth}x{$physicalHeight}!" ) .
158 // Add the source url as a comment to the thumb.
159 " -set comment " . wfEscapeShellArg( $this->escapeMagickProperty( $comment ) ) .
160 " -depth 8 $sharpen " .
161 wfEscapeShellArg( $this->escapeMagickOutput( $dstPath ) ) . " 2>&1";
162 wfDebug( __METHOD__.": running ImageMagick: $cmd\n" );
163 wfProfileIn( 'convert' );
164 $err = wfShellExec( $cmd, $retval );
165 wfProfileOut( 'convert' );
166 } elseif( $scaler == 'custom' ) {
167 # Use a custom convert command
168 # Variables: %s %d %w %h
169 $src = wfEscapeShellArg( $srcPath );
170 $dst = wfEscapeShellArg( $dstPath );
171 $cmd = $wgCustomConvertCommand;
172 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
173 $cmd = str_replace( '%h', $physicalHeight, str_replace( '%w', $physicalWidth, $cmd ) ); # Size
174 wfDebug( __METHOD__.": Running custom convert command $cmd\n" );
175 wfProfileIn( 'convert' );
176 $err = wfShellExec( $cmd, $retval );
177 wfProfileOut( 'convert' );
178 } else /* $scaler == 'gd' */ {
179 # Use PHP's builtin GD library functions.
181 # First find out what kind of file this is, and select the correct
182 # input routine for this.
185 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
186 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( __CLASS__, 'imageJpegWrapper' ) ),
187 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
188 'image/vnd.wap.wbmp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
189 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
191 if( !isset( $typemap[$mimeType] ) ) {
192 $err = 'Image type not supported';
194 $errMsg = wfMsg ( 'thumbnail_image-type' );
195 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $errMsg );
197 list( $loader, $colorStyle, $saveType ) = $typemap[$mimeType];
199 if( !function_exists( $loader ) ) {
200 $err = "Incomplete GD library configuration: missing function $loader";
202 $errMsg = wfMsg ( 'thumbnail_gd-library', $loader );
203 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $errMsg );
206 if ( !file_exists( $srcPath ) ) {
207 $err = "File seems to be missing: $srcPath";
209 $errMsg = wfMsg ( 'thumbnail_image-missing', $srcPath );
210 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $errMsg );
213 $src_image = call_user_func( $loader, $srcPath );
214 $dst_image = imagecreatetruecolor( $physicalWidth, $physicalHeight );
216 // Initialise the destination image to transparent instead of
217 // the default solid black, to support PNG and GIF transparency nicely
218 $background = imagecolorallocate( $dst_image, 0, 0, 0 );
219 imagecolortransparent( $dst_image, $background );
220 imagealphablending( $dst_image, false );
222 if( $colorStyle == 'palette' ) {
223 // Don't resample for paletted GIF images.
224 // It may just uglify them, and completely breaks transparency.
225 imagecopyresized( $dst_image, $src_image,
227 $physicalWidth, $physicalHeight, imagesx( $src_image ), imagesy( $src_image ) );
229 imagecopyresampled( $dst_image, $src_image,
231 $physicalWidth, $physicalHeight, imagesx( $src_image ), imagesy( $src_image ) );
234 imagesavealpha( $dst_image, true );
236 call_user_func( $saveType, $dst_image, $dstPath );
237 imagedestroy( $dst_image );
238 imagedestroy( $src_image );
242 $removed = $this->removeBadFile( $dstPath, $retval );
243 if ( $retval != 0 || $removed ) {
244 wfDebugLog( 'thumbnail',
245 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
246 wfHostname(), $retval, trim($err), $cmd ) );
247 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $err );
249 return new ThumbnailImage( $image, $dstUrl, $clientWidth, $clientHeight, $dstPath );
254 * Escape a string for ImageMagick's property input (e.g. -set -comment)
255 * See InterpretImageProperties() in magick/property.c
257 function escapeMagickProperty( $s ) {
258 // Double the backslashes
259 $s = str_replace( '\\', '\\\\', $s );
260 // Double the percents
261 $s = str_replace( '%', '%%', $s );
262 // Escape initial - or @
263 if ( strlen( $s ) > 0 && ( $s[0] === '-' || $s[0] === '@' ) ) {
270 * Escape a string for ImageMagick's input filenames. See ExpandFilenames()
271 * and GetPathComponent() in magick/utility.c.
273 * This won't work with an initial ~ or @, so input files should be prefixed
274 * with the directory name.
276 * Glob character unescaping is broken in ImageMagick before 6.6.1-5, but
277 * it's broken in a way that doesn't involve trying to convert every file
278 * in a directory, so we're better off escaping and waiting for the bugfix
279 * to filter down to users.
281 * @param $path string The file path
282 * @param $scene string The scene specification, or false if there is none
284 function escapeMagickInput( $path, $scene = false ) {
285 # Die on initial metacharacters (caller should prepend path)
286 $firstChar = substr( $path, 0, 1 );
287 if ( $firstChar === '~' || $firstChar === '@' ) {
288 throw new MWException( __METHOD__.': cannot escape this path name' );
292 $path = preg_replace( '/[*?\[\]{}]/', '\\\\\0', $path );
294 return $this->escapeMagickPath( $path, $scene );
298 * Escape a string for ImageMagick's output filename. See
299 * InterpretImageFilename() in magick/image.c.
301 function escapeMagickOutput( $path, $scene = false ) {
302 $path = str_replace( '%', '%%', $path );
303 return $this->escapeMagickPath( $path, $scene );
307 * Armour a string against ImageMagick's GetPathComponent(). This is a
308 * helper function for escapeMagickInput() and escapeMagickOutput().
310 * @param $path string The file path
311 * @param $scene string The scene specification, or false if there is none
313 protected function escapeMagickPath( $path, $scene = false ) {
314 # Die on format specifiers (other than drive letters). The regex is
315 # meant to match all the formats you get from "convert -list format"
316 if ( preg_match( '/^([a-zA-Z0-9-]+):/', $path, $m ) ) {
317 if ( wfIsWindows() && is_dir( $m[0] ) ) {
318 // OK, it's a drive letter
319 // ImageMagick has a similar exception, see IsMagickConflict()
321 throw new MWException( __METHOD__.': unexpected colon character in path name' );
325 # If there are square brackets, add a do-nothing scene specification
326 # to force a literal interpretation
327 if ( $scene === false ) {
328 if ( strpos( $path, '[' ) !== false ) {
337 static function imageJpegWrapper( $dst_image, $thumbPath ) {
338 imageinterlace( $dst_image );
339 imagejpeg( $dst_image, $thumbPath, 95 );
343 function getMetadata( $image, $filename ) {
345 if( $wgShowEXIF && file_exists( $filename ) ) {
346 $exif = new Exif( $filename );
347 $data = $exif->getFilteredData();
349 $data['MEDIAWIKI_EXIF_VERSION'] = Exif::version();
350 return serialize( $data );
359 function getMetadataType( $image ) {
363 function isMetadataValid( $image, $metadata ) {
365 if ( !$wgShowEXIF ) {
366 # Metadata disabled and so an empty field is expected
369 if ( $metadata === '0' ) {
370 # Special value indicating that there is no EXIF data in the file
373 $exif = @unserialize( $metadata );
374 if ( !isset( $exif['MEDIAWIKI_EXIF_VERSION'] ) ||
375 $exif['MEDIAWIKI_EXIF_VERSION'] != Exif::version() )
378 wfDebug( __METHOD__.": wrong version\n" );
385 * Get a list of EXIF metadata items which should be displayed when
386 * the metadata table is collapsed.
388 * @return array of strings
391 function visibleMetadataFields() {
393 $lines = explode( "\n", wfMsgForContent( 'metadata-fields' ) );
394 foreach( $lines as $line ) {
396 if( preg_match( '/^\\*\s*(.*?)\s*$/', $line, $matches ) ) {
397 $fields[] = $matches[1];
400 $fields = array_map( 'strtolower', $fields );
404 function formatMetadata( $image ) {
406 'visible' => array(),
407 'collapsed' => array()
409 $metadata = $image->getMetadata();
413 $exif = unserialize( $metadata );
417 unset( $exif['MEDIAWIKI_EXIF_VERSION'] );
418 $format = new FormatExif( $exif );
420 $formatted = $format->getFormattedData();
421 // Sort fields into visible and collapsed
422 $visibleFields = $this->visibleMetadataFields();
423 foreach ( $formatted as $name => $value ) {
424 $tag = strtolower( $name );
425 self::addMeta( $result,
426 in_array( $tag, $visibleFields ) ? 'visible' : 'collapsed',