170c0c5455fe07b9807815a2ad7f421e9cb489c4
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 if ( $mimeType == 'image/jpeg' ) {
123 $quality = "-quality 80"; // 80%
124 # Sharpening, see bug 6193
125 if ( ( $physicalWidth +
$physicalHeight ) / ( $srcWidth +
$srcHeight ) < $wgSharpenReductionThreshold ) {
126 $sharpen = "-sharpen " . wfEscapeShellArg( $wgSharpenParameter );
128 } elseif ( $mimeType == 'image/png' ) {
129 $quality = "-quality 95"; // zlib 9, adaptive filtering
130 } elseif( $mimeType == 'image/gif' ) {
131 if( $this->getImageArea( $image, $srcWidth, $srcHeight ) > $wgMaxAnimatedGifArea ) {
132 // Extract initial frame only; we're so big it'll
133 // be a total drag. :P
136 // Coalesce is needed to scale animated GIFs properly (bug 1017).
137 $animation = ' -coalesce ';
141 if ( strval( $wgImageMagickTempDir ) !== '' ) {
142 $tempEnv = 'MAGICK_TMPDIR=' . wfEscapeShellArg( $wgImageMagickTempDir ) . ' ';
147 # Specify white background color, will be used for transparent images
148 # in Internet Explorer/Windows instead of default black.
150 # Note, we specify "-size {$physicalWidth}" and NOT "-size {$physicalWidth}x{$physicalHeight}".
151 # It seems that ImageMagick has a bug wherein it produces thumbnails of
152 # the wrong size in the second case.
156 wfEscapeShellArg( $wgImageMagickConvertCommand ) .
157 " {$quality} -background white -size {$physicalWidth} ".
158 wfEscapeShellArg( $this->escapeMagickInput( $srcPath, $scene ) ) .
160 // For the -resize option a "!" is needed to force exact size,
161 // or ImageMagick may decide your ratio is wrong and slice off
163 " -thumbnail " . wfEscapeShellArg( "{$physicalWidth}x{$physicalHeight}!" ) .
164 // Add the source url as a comment to the thumb.
165 " -set comment " . wfEscapeShellArg( $this->escapeMagickProperty( $comment ) ) .
166 " -depth 8 $sharpen " .
167 wfEscapeShellArg( $this->escapeMagickOutput( $dstPath ) ) . " 2>&1";
168 wfDebug( __METHOD__
.": running ImageMagick: $cmd\n" );
169 wfProfileIn( 'convert' );
170 $err = wfShellExec( $cmd, $retval );
171 wfProfileOut( 'convert' );
172 } elseif( $scaler == 'custom' ) {
173 # Use a custom convert command
174 # Variables: %s %d %w %h
175 $src = wfEscapeShellArg( $srcPath );
176 $dst = wfEscapeShellArg( $dstPath );
177 $cmd = $wgCustomConvertCommand;
178 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
179 $cmd = str_replace( '%h', $physicalHeight, str_replace( '%w', $physicalWidth, $cmd ) ); # Size
180 wfDebug( __METHOD__
.": Running custom convert command $cmd\n" );
181 wfProfileIn( 'convert' );
182 $err = wfShellExec( $cmd, $retval );
183 wfProfileOut( 'convert' );
184 } else /* $scaler == 'gd' */ {
185 # Use PHP's builtin GD library functions.
187 # First find out what kind of file this is, and select the correct
188 # input routine for this.
191 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
192 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( __CLASS__
, 'imageJpegWrapper' ) ),
193 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
194 'image/vnd.wap.wbmp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
195 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
197 if( !isset( $typemap[$mimeType] ) ) {
198 $err = 'Image type not supported';
200 $errMsg = wfMsg ( 'thumbnail_image-type' );
201 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $errMsg );
203 list( $loader, $colorStyle, $saveType ) = $typemap[$mimeType];
205 if( !function_exists( $loader ) ) {
206 $err = "Incomplete GD library configuration: missing function $loader";
208 $errMsg = wfMsg ( 'thumbnail_gd-library', $loader );
209 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $errMsg );
212 if ( !file_exists( $srcPath ) ) {
213 $err = "File seems to be missing: $srcPath";
215 $errMsg = wfMsg ( 'thumbnail_image-missing', $srcPath );
216 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $errMsg );
219 $src_image = call_user_func( $loader, $srcPath );
220 $dst_image = imagecreatetruecolor( $physicalWidth, $physicalHeight );
222 // Initialise the destination image to transparent instead of
223 // the default solid black, to support PNG and GIF transparency nicely
224 $background = imagecolorallocate( $dst_image, 0, 0, 0 );
225 imagecolortransparent( $dst_image, $background );
226 imagealphablending( $dst_image, false );
228 if( $colorStyle == 'palette' ) {
229 // Don't resample for paletted GIF images.
230 // It may just uglify them, and completely breaks transparency.
231 imagecopyresized( $dst_image, $src_image,
233 $physicalWidth, $physicalHeight, imagesx( $src_image ), imagesy( $src_image ) );
235 imagecopyresampled( $dst_image, $src_image,
237 $physicalWidth, $physicalHeight, imagesx( $src_image ), imagesy( $src_image ) );
240 imagesavealpha( $dst_image, true );
242 call_user_func( $saveType, $dst_image, $dstPath );
243 imagedestroy( $dst_image );
244 imagedestroy( $src_image );
248 $removed = $this->removeBadFile( $dstPath, $retval );
249 if ( $retval != 0 ||
$removed ) {
250 wfDebugLog( 'thumbnail',
251 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
252 wfHostname(), $retval, trim($err), $cmd ) );
253 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $err );
255 return new ThumbnailImage( $image, $dstUrl, $clientWidth, $clientHeight, $dstPath );
260 * Escape a string for ImageMagick's property input (e.g. -set -comment)
261 * See InterpretImageProperties() in magick/property.c
263 function escapeMagickProperty( $s ) {
264 // Double the backslashes
265 $s = str_replace( '\\', '\\\\', $s );
266 // Double the percents
267 $s = str_replace( '%', '%%', $s );
268 // Escape initial - or @
269 if ( strlen( $s ) > 0 && ( $s[0] === '-' ||
$s[0] === '@' ) ) {
276 * Escape a string for ImageMagick's input filenames. See ExpandFilenames()
277 * and GetPathComponent() in magick/utility.c.
279 * This won't work with an initial ~ or @, so input files should be prefixed
280 * with the directory name.
282 * Glob character unescaping is broken in ImageMagick before 6.6.1-5, but
283 * it's broken in a way that doesn't involve trying to convert every file
284 * in a directory, so we're better off escaping and waiting for the bugfix
285 * to filter down to users.
287 * @param $path string The file path
288 * @param $scene string The scene specification, or false if there is none
290 function escapeMagickInput( $path, $scene = false ) {
291 # Die on initial metacharacters (caller should prepend path)
292 $firstChar = substr( $path, 0, 1 );
293 if ( $firstChar === '~' ||
$firstChar === '@' ) {
294 throw new MWException( __METHOD__
.': cannot escape this path name' );
298 $path = preg_replace( '/[*?\[\]{}]/', '\\\\\0', $path );
300 return $this->escapeMagickPath( $path, $scene );
304 * Escape a string for ImageMagick's output filename. See
305 * InterpretImageFilename() in magick/image.c.
307 function escapeMagickOutput( $path, $scene = false ) {
308 $path = str_replace( '%', '%%', $path );
309 return $this->escapeMagickPath( $path, $scene );
313 * Armour a string against ImageMagick's GetPathComponent(). This is a
314 * helper function for escapeMagickInput() and escapeMagickOutput().
316 * @param $path string The file path
317 * @param $scene string The scene specification, or false if there is none
319 protected function escapeMagickPath( $path, $scene = false ) {
320 # Die on format specifiers (other than drive letters). The regex is
321 # meant to match all the formats you get from "convert -list format"
322 if ( preg_match( '/^([a-zA-Z0-9-]+):/', $path, $m ) ) {
323 if ( wfIsWindows() && is_dir( $m[0] ) ) {
324 // OK, it's a drive letter
325 // ImageMagick has a similar exception, see IsMagickConflict()
327 throw new MWException( __METHOD__
.': unexpected colon character in path name' );
331 # If there are square brackets, add a do-nothing scene specification
332 # to force a literal interpretation
333 if ( $scene === false ) {
334 if ( strpos( $path, '[' ) !== false ) {
343 static function imageJpegWrapper( $dst_image, $thumbPath ) {
344 imageinterlace( $dst_image );
345 imagejpeg( $dst_image, $thumbPath, 95 );
349 function getMetadata( $image, $filename ) {
351 if( $wgShowEXIF && file_exists( $filename ) ) {
352 $exif = new Exif( $filename );
353 $data = $exif->getFilteredData();
355 $data['MEDIAWIKI_EXIF_VERSION'] = Exif
::version();
356 return serialize( $data );
365 function getMetadataType( $image ) {
369 function isMetadataValid( $image, $metadata ) {
371 if ( !$wgShowEXIF ) {
372 # Metadata disabled and so an empty field is expected
375 if ( $metadata === '0' ) {
376 # Special value indicating that there is no EXIF data in the file
379 wfSuppressWarnings();
380 $exif = unserialize( $metadata );
382 if ( !isset( $exif['MEDIAWIKI_EXIF_VERSION'] ) ||
383 $exif['MEDIAWIKI_EXIF_VERSION'] != Exif
::version() )
386 wfDebug( __METHOD__
.": wrong version\n" );
393 * Get a list of EXIF metadata items which should be displayed when
394 * the metadata table is collapsed.
396 * @return array of strings
399 function visibleMetadataFields() {
401 $lines = explode( "\n", wfMsgForContent( 'metadata-fields' ) );
402 foreach( $lines as $line ) {
404 if( preg_match( '/^\\*\s*(.*?)\s*$/', $line, $matches ) ) {
405 $fields[] = $matches[1];
408 $fields = array_map( 'strtolower', $fields );
412 function formatMetadata( $image ) {
414 'visible' => array(),
415 'collapsed' => array()
417 $metadata = $image->getMetadata();
421 $exif = unserialize( $metadata );
425 unset( $exif['MEDIAWIKI_EXIF_VERSION'] );
426 $format = new FormatExif( $exif );
428 $formatted = $format->getFormattedData();
429 // Sort fields into visible and collapsed
430 $visibleFields = $this->visibleMetadataFields();
431 foreach ( $formatted as $name => $value ) {
432 $tag = strtolower( $name );
433 self
::addMeta( $result,
434 in_array( $tag, $visibleFields ) ?
'visible' : 'collapsed',