3 * Generic handler for bitmap images.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * Generic handler for bitmap images
29 class BitmapHandler
extends TransformationalImageHandler
{
32 * Returns which scaler type should be used. Creates parent directories
33 * for $dstPath and returns 'client' on error
35 * @param string $dstPath
36 * @param bool $checkDstPath
37 * @return string|Callable One of client, im, custom, gd, imext or an array( object, method )
39 protected function getScalerType( $dstPath, $checkDstPath = true ) {
40 global $wgUseImageResize, $wgUseImageMagick, $wgCustomConvertCommand;
42 if ( !$dstPath && $checkDstPath ) {
43 # No output path available, client side scaling only
45 } elseif ( !$wgUseImageResize ) {
47 } elseif ( $wgUseImageMagick ) {
49 } elseif ( $wgCustomConvertCommand ) {
51 } elseif ( function_exists( 'imagecreatetruecolor' ) ) {
53 } elseif ( class_exists( 'Imagick' ) ) {
62 function makeParamString( $params ) {
63 $res = parent
::makeParamString( $params );
64 if ( isset( $params['interlace'] ) && $params['interlace'] ) {
65 return "interlaced-{$res}";
71 function parseParamString( $str ) {
72 $remainder = preg_replace( '/^interlaced-/', '', $str );
73 $params = parent
::parseParamString( $remainder );
74 if ( $params === false ) {
77 $params['interlace'] = $str !== $remainder;
81 function validateParam( $name, $value ) {
82 if ( $name === 'interlace' ) {
83 return $value === false ||
$value === true;
85 return parent
::validateParam( $name, $value );
91 * @param array $params
94 function normaliseParams( $image, &$params ) {
95 global $wgMaxInterlacingAreas;
96 if ( !parent
::normaliseParams( $image, $params ) ) {
99 $mimeType = $image->getMimeType();
100 $interlace = isset( $params['interlace'] ) && $params['interlace']
101 && isset( $wgMaxInterlacingAreas[$mimeType] )
102 && $this->getImageArea( $image ) <= $wgMaxInterlacingAreas[$mimeType];
103 $params['interlace'] = $interlace;
108 * Transform an image using ImageMagick
110 * @param File $image File associated with this thumbnail
111 * @param array $params Array with scaler params
113 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
115 protected function transformImageMagick( $image, $params ) {
117 global $wgSharpenReductionThreshold, $wgSharpenParameter, $wgMaxAnimatedGifArea,
118 $wgImageMagickTempDir, $wgImageMagickConvertCommand, $wgMaxInterlacingAreas;
123 $animation_pre = array();
124 $animation_post = array();
125 $decoderHint = array();
127 if ( $params['mimeType'] == 'image/jpeg' ) {
128 $qualityVal = isset( $params['quality'] ) ?
(string)$params['quality'] : null;
129 $quality = array( '-quality', $qualityVal ?
: '80' ); // 80%
130 if ( $params['interlace'] ) {
131 $animation_post = array( '-interlace', 'JPEG' );
133 # Sharpening, see bug 6193
134 if ( ( $params['physicalWidth'] +
$params['physicalHeight'] )
135 / ( $params['srcWidth'] +
$params['srcHeight'] )
136 < $wgSharpenReductionThreshold
138 $sharpen = array( '-sharpen', $wgSharpenParameter );
140 if ( version_compare( $this->getMagickVersion(), "6.5.6" ) >= 0 ) {
141 // JPEG decoder hint to reduce memory, available since IM 6.5.6-2
142 $decoderHint = array( '-define', "jpeg:size={$params['physicalDimensions']}" );
144 } elseif ( $params['mimeType'] == 'image/png' ) {
145 $quality = array( '-quality', '95' ); // zlib 9, adaptive filtering
146 if ( $params['interlace'] ) {
147 $animation_post = array( '-interlace', 'PNG' );
149 } elseif ( $params['mimeType'] == 'image/webp' ) {
150 $quality = array( '-quality', '95' ); // zlib 9, adaptive filtering
151 } elseif ( $params['mimeType'] == 'image/gif' ) {
152 if ( $this->getImageArea( $image ) > $wgMaxAnimatedGifArea ) {
153 // Extract initial frame only; we're so big it'll
154 // be a total drag. :P
156 } elseif ( $this->isAnimatedImage( $image ) ) {
157 // Coalesce is needed to scale animated GIFs properly (bug 1017).
158 $animation_pre = array( '-coalesce' );
159 // We optimize the output, but -optimize is broken,
160 // use optimizeTransparency instead (bug 11822)
161 if ( version_compare( $this->getMagickVersion(), "6.3.5" ) >= 0 ) {
162 $animation_post = array( '-fuzz', '5%', '-layers', 'optimizeTransparency' );
165 if ( $params['interlace'] && version_compare( $this->getMagickVersion(), "6.3.4" ) >= 0
166 && !$this->isAnimatedImage( $image ) ) { // interlacing animated GIFs is a bad idea
167 $animation_post[] = '-interlace';
168 $animation_post[] = 'GIF';
170 } elseif ( $params['mimeType'] == 'image/x-xcf' ) {
171 // Before merging layers, we need to set the background
172 // to be transparent to preserve alpha, as -layers merge
173 // merges all layers on to a canvas filled with the
174 // background colour. After merging we reset the background
175 // to be white for the default background colour setting
176 // in the PNG image (which is used in old IE)
177 $animation_pre = array(
178 '-background', 'transparent',
180 '-background', 'white',
182 MediaWiki\
suppressWarnings();
183 $xcfMeta = unserialize( $image->getMetadata() );
184 MediaWiki\restoreWarnings
();
186 && isset( $xcfMeta['colorType'] )
187 && $xcfMeta['colorType'] === 'greyscale-alpha'
188 && version_compare( $this->getMagickVersion(), "6.8.9-3" ) < 0
190 // bug 66323 - Greyscale images not rendered properly.
191 // So only take the "red" channel.
192 $channelOnly = array( '-channel', 'R', '-separate' );
193 $animation_pre = array_merge( $animation_pre, $channelOnly );
197 // Use one thread only, to avoid deadlock bugs on OOM
198 $env = array( 'OMP_NUM_THREADS' => 1 );
199 if ( strval( $wgImageMagickTempDir ) !== '' ) {
200 $env['MAGICK_TMPDIR'] = $wgImageMagickTempDir;
203 $rotation = isset( $params['disableRotation'] ) ?
0 : $this->getRotation( $image );
204 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
206 $cmd = call_user_func_array( 'wfEscapeShellArg', array_merge(
207 array( $wgImageMagickConvertCommand ),
209 // Specify white background color, will be used for transparent images
210 // in Internet Explorer/Windows instead of default black.
211 array( '-background', 'white' ),
213 array( $this->escapeMagickInput( $params['srcPath'], $scene ) ),
215 // For the -thumbnail option a "!" is needed to force exact size,
216 // or ImageMagick may decide your ratio is wrong and slice off
218 array( '-thumbnail', "{$width}x{$height}!" ),
219 // Add the source url as a comment to the thumb, but don't add the flag if there's no comment
220 ( $params['comment'] !== ''
221 ?
array( '-set', 'comment', $this->escapeMagickProperty( $params['comment'] ) )
223 // T108616: Avoid exposure of local file path
224 array( '+set', 'Thumb::URI' ),
225 array( '-depth', 8 ),
227 array( '-rotate', "-$rotation" ),
229 array( $this->escapeMagickOutput( $params['dstPath'] ) ) ) );
231 wfDebug( __METHOD__
. ": running ImageMagick: $cmd\n" );
233 $err = wfShellExecWithStderr( $cmd, $retval, $env );
235 if ( $retval !== 0 ) {
236 $this->logErrorForExternalProcess( $retval, $err, $cmd );
238 return $this->getMediaTransformError( $params, "$err\nError code: $retval" );
241 return false; # No error
245 * Transform an image using the Imagick PHP extension
247 * @param File $image File associated with this thumbnail
248 * @param array $params Array with scaler params
250 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
252 protected function transformImageMagickExt( $image, $params ) {
253 global $wgSharpenReductionThreshold, $wgSharpenParameter, $wgMaxAnimatedGifArea,
254 $wgMaxInterlacingAreas;
258 $im->readImage( $params['srcPath'] );
260 if ( $params['mimeType'] == 'image/jpeg' ) {
261 // Sharpening, see bug 6193
262 if ( ( $params['physicalWidth'] +
$params['physicalHeight'] )
263 / ( $params['srcWidth'] +
$params['srcHeight'] )
264 < $wgSharpenReductionThreshold
266 // Hack, since $wgSharpenParameter is written specifically for the command line convert
267 list( $radius, $sigma ) = explode( 'x', $wgSharpenParameter );
268 $im->sharpenImage( $radius, $sigma );
270 $qualityVal = isset( $params['quality'] ) ?
(string)$params['quality'] : null;
271 $im->setCompressionQuality( $qualityVal ?
: 80 );
272 if ( $params['interlace'] ) {
273 $im->setInterlaceScheme( Imagick
::INTERLACE_JPEG
);
275 } elseif ( $params['mimeType'] == 'image/png' ) {
276 $im->setCompressionQuality( 95 );
277 if ( $params['interlace'] ) {
278 $im->setInterlaceScheme( Imagick
::INTERLACE_PNG
);
280 } elseif ( $params['mimeType'] == 'image/gif' ) {
281 if ( $this->getImageArea( $image ) > $wgMaxAnimatedGifArea ) {
282 // Extract initial frame only; we're so big it'll
283 // be a total drag. :P
284 $im->setImageScene( 0 );
285 } elseif ( $this->isAnimatedImage( $image ) ) {
286 // Coalesce is needed to scale animated GIFs properly (bug 1017).
287 $im = $im->coalesceImages();
289 // GIF interlacing is only available since 6.3.4
290 $v = Imagick
::getVersion();
291 preg_match( '/ImageMagick ([0-9]+\.[0-9]+\.[0-9]+)/', $v['versionString'], $v );
293 if ( $params['interlace'] && version_compare( $v[1], '6.3.4' ) >= 0 ) {
294 $im->setInterlaceScheme( Imagick
::INTERLACE_GIF
);
298 $rotation = isset( $params['disableRotation'] ) ?
0 : $this->getRotation( $image );
299 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
301 $im->setImageBackgroundColor( new ImagickPixel( 'white' ) );
303 // Call Imagick::thumbnailImage on each frame
304 foreach ( $im as $i => $frame ) {
305 if ( !$frame->thumbnailImage( $width, $height, /* fit */ false ) ) {
306 return $this->getMediaTransformError( $params, "Error scaling frame $i" );
309 $im->setImageDepth( 8 );
312 if ( !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) {
313 return $this->getMediaTransformError( $params, "Error rotating $rotation degrees" );
317 if ( $this->isAnimatedImage( $image ) ) {
318 wfDebug( __METHOD__
. ": Writing animated thumbnail\n" );
319 // This is broken somehow... can't find out how to fix it
320 $result = $im->writeImages( $params['dstPath'], true );
322 $result = $im->writeImage( $params['dstPath'] );
325 return $this->getMediaTransformError( $params,
326 "Unable to write thumbnail to {$params['dstPath']}" );
328 } catch ( ImagickException
$e ) {
329 return $this->getMediaTransformError( $params, $e->getMessage() );
336 * Transform an image using a custom command
338 * @param File $image File associated with this thumbnail
339 * @param array $params Array with scaler params
341 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
343 protected function transformCustom( $image, $params ) {
344 # Use a custom convert command
345 global $wgCustomConvertCommand;
347 # Variables: %s %d %w %h
348 $src = wfEscapeShellArg( $params['srcPath'] );
349 $dst = wfEscapeShellArg( $params['dstPath'] );
350 $cmd = $wgCustomConvertCommand;
351 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
352 $cmd = str_replace( '%h', wfEscapeShellArg( $params['physicalHeight'] ),
353 str_replace( '%w', wfEscapeShellArg( $params['physicalWidth'] ), $cmd ) ); # Size
354 wfDebug( __METHOD__
. ": Running custom convert command $cmd\n" );
356 $err = wfShellExecWithStderr( $cmd, $retval );
358 if ( $retval !== 0 ) {
359 $this->logErrorForExternalProcess( $retval, $err, $cmd );
361 return $this->getMediaTransformError( $params, $err );
364 return false; # No error
368 * Transform an image using the built in GD library
370 * @param File $image File associated with this thumbnail
371 * @param array $params Array with scaler params
373 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
375 protected function transformGd( $image, $params ) {
376 # Use PHP's builtin GD library functions.
377 # First find out what kind of file this is, and select the correct
378 # input routine for this.
381 'image/gif' => array( 'imagecreatefromgif', 'palette', false, 'imagegif' ),
382 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', true,
383 array( __CLASS__
, 'imageJpegWrapper' ) ),
384 'image/png' => array( 'imagecreatefrompng', 'bits', false, 'imagepng' ),
385 'image/vnd.wap.wbmp' => array( 'imagecreatefromwbmp', 'palette', false, 'imagewbmp' ),
386 'image/xbm' => array( 'imagecreatefromxbm', 'palette', false, 'imagexbm' ),
389 if ( !isset( $typemap[$params['mimeType']] ) ) {
390 $err = 'Image type not supported';
392 $errMsg = wfMessage( 'thumbnail_image-type' )->text();
394 return $this->getMediaTransformError( $params, $errMsg );
396 list( $loader, $colorStyle, $useQuality, $saveType ) = $typemap[$params['mimeType']];
398 if ( !function_exists( $loader ) ) {
399 $err = "Incomplete GD library configuration: missing function $loader";
401 $errMsg = wfMessage( 'thumbnail_gd-library', $loader )->text();
403 return $this->getMediaTransformError( $params, $errMsg );
406 if ( !file_exists( $params['srcPath'] ) ) {
407 $err = "File seems to be missing: {$params['srcPath']}";
409 $errMsg = wfMessage( 'thumbnail_image-missing', $params['srcPath'] )->text();
411 return $this->getMediaTransformError( $params, $errMsg );
414 $src_image = call_user_func( $loader, $params['srcPath'] );
416 $rotation = function_exists( 'imagerotate' ) && !isset( $params['disableRotation'] ) ?
417 $this->getRotation( $image ) :
419 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
420 $dst_image = imagecreatetruecolor( $width, $height );
422 // Initialise the destination image to transparent instead of
423 // the default solid black, to support PNG and GIF transparency nicely
424 $background = imagecolorallocate( $dst_image, 0, 0, 0 );
425 imagecolortransparent( $dst_image, $background );
426 imagealphablending( $dst_image, false );
428 if ( $colorStyle == 'palette' ) {
429 // Don't resample for paletted GIF images.
430 // It may just uglify them, and completely breaks transparency.
431 imagecopyresized( $dst_image, $src_image,
434 imagesx( $src_image ), imagesy( $src_image ) );
436 imagecopyresampled( $dst_image, $src_image,
439 imagesx( $src_image ), imagesy( $src_image ) );
442 if ( $rotation %
360 != 0 && $rotation %
90 == 0 ) {
443 $rot_image = imagerotate( $dst_image, $rotation, 0 );
444 imagedestroy( $dst_image );
445 $dst_image = $rot_image;
448 imagesavealpha( $dst_image, true );
450 $funcParams = array( $dst_image, $params['dstPath'] );
451 if ( $useQuality && isset( $params['quality'] ) ) {
452 $funcParams[] = $params['quality'];
454 call_user_func_array( $saveType, $funcParams );
456 imagedestroy( $dst_image );
457 imagedestroy( $src_image );
459 return false; # No error
463 * Callback for transformGd when transforming jpeg images.
465 // FIXME: transformImageMagick() & transformImageMagickExt() uses JPEG quality 80, here it's 95?
466 static function imageJpegWrapper( $dst_image, $thumbPath, $quality = 95 ) {
467 imageinterlace( $dst_image );
468 imagejpeg( $dst_image, $thumbPath, $quality );
472 * Returns whether the current scaler supports rotation (im and gd do)
476 public function canRotate() {
477 $scaler = $this->getScalerType( null, false );
480 # ImageMagick supports autorotation
483 # Imagick::rotateImage
486 # GD's imagerotate function is used to rotate images, but not
487 # all precompiled PHP versions have that function
488 return function_exists( 'imagerotate' );
490 # Other scalers don't support rotation
496 * @see $wgEnableAutoRotation
497 * @return bool Whether auto rotation is enabled
499 public function autoRotateEnabled() {
500 global $wgEnableAutoRotation;
502 if ( $wgEnableAutoRotation === null ) {
503 // Only enable auto-rotation when we actually can
504 return $this->canRotate();
507 return $wgEnableAutoRotation;
512 * @param array $params Rotate parameters.
513 * 'rotation' clockwise rotation in degrees, allowed are multiples of 90
517 public function rotate( $file, $params ) {
518 global $wgImageMagickConvertCommand;
520 $rotation = ( $params['rotation'] +
$this->getRotation( $file ) ) %
360;
523 $scaler = $this->getScalerType( null, false );
526 $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . " " .
527 wfEscapeShellArg( $this->escapeMagickInput( $params['srcPath'], $scene ) ) .
528 " -rotate " . wfEscapeShellArg( "-$rotation" ) . " " .
529 wfEscapeShellArg( $this->escapeMagickOutput( $params['dstPath'] ) );
530 wfDebug( __METHOD__
. ": running ImageMagick: $cmd\n" );
532 $err = wfShellExecWithStderr( $cmd, $retval );
533 if ( $retval !== 0 ) {
534 $this->logErrorForExternalProcess( $retval, $err, $cmd );
536 return new MediaTransformError( 'thumbnail_error', 0, 0, $err );
542 $im->readImage( $params['srcPath'] );
543 if ( !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) {
544 return new MediaTransformError( 'thumbnail_error', 0, 0,
545 "Error rotating $rotation degrees" );
547 $result = $im->writeImage( $params['dstPath'] );
549 return new MediaTransformError( 'thumbnail_error', 0, 0,
550 "Unable to write image to {$params['dstPath']}" );
555 return new MediaTransformError( 'thumbnail_error', 0, 0,
556 "$scaler rotation not implemented" );