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;
83 * @param array $params
86 function normaliseParams( $image, &$params ) {
87 global $wgMaxInterlacingAreas;
88 if ( !parent
::normaliseParams( $image, $params ) ) {
91 $mimeType = $image->getMimeType();
92 $interlace = isset( $params['interlace'] ) && $params['interlace']
93 && isset( $wgMaxInterlacingAreas[$mimeType] )
94 && $this->getImageArea( $image ) <= $wgMaxInterlacingAreas[$mimeType];
95 $params['interlace'] = $interlace;
100 * Transform an image using ImageMagick
102 * @param File $image File associated with this thumbnail
103 * @param array $params Array with scaler params
105 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
107 protected function transformImageMagick( $image, $params ) {
109 global $wgSharpenReductionThreshold, $wgSharpenParameter, $wgMaxAnimatedGifArea,
110 $wgImageMagickTempDir, $wgImageMagickConvertCommand, $wgMaxInterlacingAreas;
115 $animation_pre = array();
116 $animation_post = array();
117 $decoderHint = array();
119 if ( $params['mimeType'] == 'image/jpeg' ) {
120 $qualityVal = isset( $params['quality'] ) ?
(string)$params['quality'] : null;
121 $quality = array( '-quality', $qualityVal ?
: '80' ); // 80%
122 if ( $params['interlace'] ) {
123 $animation_post = array( '-interlace', 'JPEG' );
125 # Sharpening, see bug 6193
126 if ( ( $params['physicalWidth'] +
$params['physicalHeight'] )
127 / ( $params['srcWidth'] +
$params['srcHeight'] )
128 < $wgSharpenReductionThreshold
130 $sharpen = array( '-sharpen', $wgSharpenParameter );
132 if ( version_compare( $this->getMagickVersion(), "6.5.6" ) >= 0 ) {
133 // JPEG decoder hint to reduce memory, available since IM 6.5.6-2
134 $decoderHint = array( '-define', "jpeg:size={$params['physicalDimensions']}" );
136 } elseif ( $params['mimeType'] == 'image/png' ) {
137 $quality = array( '-quality', '95' ); // zlib 9, adaptive filtering
138 if ( $params['interlace'] ) {
139 $animation_post = array( '-interlace', 'PNG' );
141 } elseif ( $params['mimeType'] == 'image/webp' ) {
142 $quality = array( '-quality', '95' ); // zlib 9, adaptive filtering
143 } elseif ( $params['mimeType'] == 'image/gif' ) {
144 if ( $this->getImageArea( $image ) > $wgMaxAnimatedGifArea ) {
145 // Extract initial frame only; we're so big it'll
146 // be a total drag. :P
148 } elseif ( $this->isAnimatedImage( $image ) ) {
149 // Coalesce is needed to scale animated GIFs properly (bug 1017).
150 $animation_pre = array( '-coalesce' );
151 // We optimize the output, but -optimize is broken,
152 // use optimizeTransparency instead (bug 11822)
153 if ( version_compare( $this->getMagickVersion(), "6.3.5" ) >= 0 ) {
154 $animation_post = array( '-fuzz', '5%', '-layers', 'optimizeTransparency' );
157 if ( $params['interlace'] && version_compare( $this->getMagickVersion(), "6.3.4" ) >= 0
158 && !$this->isAnimatedImage( $image ) ) { // interlacing animated GIFs is a bad idea
159 $animation_post[] = '-interlace';
160 $animation_post[] = 'GIF';
162 } elseif ( $params['mimeType'] == 'image/x-xcf' ) {
163 // Before merging layers, we need to set the background
164 // to be transparent to preserve alpha, as -layers merge
165 // merges all layers on to a canvas filled with the
166 // background colour. After merging we reset the background
167 // to be white for the default background colour setting
168 // in the PNG image (which is used in old IE)
169 $animation_pre = array(
170 '-background', 'transparent',
172 '-background', 'white',
174 MediaWiki\
suppressWarnings();
175 $xcfMeta = unserialize( $image->getMetadata() );
176 MediaWiki\restoreWarnings
();
178 && isset( $xcfMeta['colorType'] )
179 && $xcfMeta['colorType'] === 'greyscale-alpha'
180 && version_compare( $this->getMagickVersion(), "6.8.9-3" ) < 0
182 // bug 66323 - Greyscale images not rendered properly.
183 // So only take the "red" channel.
184 $channelOnly = array( '-channel', 'R', '-separate' );
185 $animation_pre = array_merge( $animation_pre, $channelOnly );
189 // Use one thread only, to avoid deadlock bugs on OOM
190 $env = array( 'OMP_NUM_THREADS' => 1 );
191 if ( strval( $wgImageMagickTempDir ) !== '' ) {
192 $env['MAGICK_TMPDIR'] = $wgImageMagickTempDir;
195 $rotation = isset( $params['disableRotation'] ) ?
0 : $this->getRotation( $image );
196 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
198 $cmd = call_user_func_array( 'wfEscapeShellArg', array_merge(
199 array( $wgImageMagickConvertCommand ),
201 // Specify white background color, will be used for transparent images
202 // in Internet Explorer/Windows instead of default black.
203 array( '-background', 'white' ),
205 array( $this->escapeMagickInput( $params['srcPath'], $scene ) ),
207 // For the -thumbnail option a "!" is needed to force exact size,
208 // or ImageMagick may decide your ratio is wrong and slice off
210 array( '-thumbnail', "{$width}x{$height}!" ),
211 // Add the source url as a comment to the thumb, but don't add the flag if there's no comment
212 ( $params['comment'] !== ''
213 ?
array( '-set', 'comment', $this->escapeMagickProperty( $params['comment'] ) )
215 // T108616: Avoid exposure of local file path
216 array( '+set', 'Thumb::URI' ),
217 array( '-depth', 8 ),
219 array( '-rotate', "-$rotation" ),
221 array( $this->escapeMagickOutput( $params['dstPath'] ) ) ) );
223 wfDebug( __METHOD__
. ": running ImageMagick: $cmd\n" );
225 $err = wfShellExecWithStderr( $cmd, $retval, $env );
227 if ( $retval !== 0 ) {
228 $this->logErrorForExternalProcess( $retval, $err, $cmd );
230 return $this->getMediaTransformError( $params, "$err\nError code: $retval" );
233 return false; # No error
237 * Transform an image using the Imagick PHP extension
239 * @param File $image File associated with this thumbnail
240 * @param array $params Array with scaler params
242 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
244 protected function transformImageMagickExt( $image, $params ) {
245 global $wgSharpenReductionThreshold, $wgSharpenParameter, $wgMaxAnimatedGifArea,
246 $wgMaxInterlacingAreas;
250 $im->readImage( $params['srcPath'] );
252 if ( $params['mimeType'] == 'image/jpeg' ) {
253 // Sharpening, see bug 6193
254 if ( ( $params['physicalWidth'] +
$params['physicalHeight'] )
255 / ( $params['srcWidth'] +
$params['srcHeight'] )
256 < $wgSharpenReductionThreshold
258 // Hack, since $wgSharpenParameter is written specifically for the command line convert
259 list( $radius, $sigma ) = explode( 'x', $wgSharpenParameter );
260 $im->sharpenImage( $radius, $sigma );
262 $qualityVal = isset( $params['quality'] ) ?
(string)$params['quality'] : null;
263 $im->setCompressionQuality( $qualityVal ?
: 80 );
264 if ( $params['interlace'] ) {
265 $im->setInterlaceScheme( Imagick
::INTERLACE_JPEG
);
267 } elseif ( $params['mimeType'] == 'image/png' ) {
268 $im->setCompressionQuality( 95 );
269 if ( $params['interlace'] ) {
270 $im->setInterlaceScheme( Imagick
::INTERLACE_PNG
);
272 } elseif ( $params['mimeType'] == 'image/gif' ) {
273 if ( $this->getImageArea( $image ) > $wgMaxAnimatedGifArea ) {
274 // Extract initial frame only; we're so big it'll
275 // be a total drag. :P
276 $im->setImageScene( 0 );
277 } elseif ( $this->isAnimatedImage( $image ) ) {
278 // Coalesce is needed to scale animated GIFs properly (bug 1017).
279 $im = $im->coalesceImages();
281 // GIF interlacing is only available since 6.3.4
282 $v = Imagick
::getVersion();
283 preg_match( '/ImageMagick ([0-9]+\.[0-9]+\.[0-9]+)/', $v['versionString'], $v );
285 if ( $params['interlace'] && version_compare( $v[1], '6.3.4' ) >= 0 ) {
286 $im->setInterlaceScheme( Imagick
::INTERLACE_GIF
);
290 $rotation = isset( $params['disableRotation'] ) ?
0 : $this->getRotation( $image );
291 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
293 $im->setImageBackgroundColor( new ImagickPixel( 'white' ) );
295 // Call Imagick::thumbnailImage on each frame
296 foreach ( $im as $i => $frame ) {
297 if ( !$frame->thumbnailImage( $width, $height, /* fit */ false ) ) {
298 return $this->getMediaTransformError( $params, "Error scaling frame $i" );
301 $im->setImageDepth( 8 );
304 if ( !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) {
305 return $this->getMediaTransformError( $params, "Error rotating $rotation degrees" );
309 if ( $this->isAnimatedImage( $image ) ) {
310 wfDebug( __METHOD__
. ": Writing animated thumbnail\n" );
311 // This is broken somehow... can't find out how to fix it
312 $result = $im->writeImages( $params['dstPath'], true );
314 $result = $im->writeImage( $params['dstPath'] );
317 return $this->getMediaTransformError( $params,
318 "Unable to write thumbnail to {$params['dstPath']}" );
320 } catch ( ImagickException
$e ) {
321 return $this->getMediaTransformError( $params, $e->getMessage() );
328 * Transform an image using a custom command
330 * @param File $image File associated with this thumbnail
331 * @param array $params Array with scaler params
333 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
335 protected function transformCustom( $image, $params ) {
336 # Use a custom convert command
337 global $wgCustomConvertCommand;
339 # Variables: %s %d %w %h
340 $src = wfEscapeShellArg( $params['srcPath'] );
341 $dst = wfEscapeShellArg( $params['dstPath'] );
342 $cmd = $wgCustomConvertCommand;
343 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
344 $cmd = str_replace( '%h', wfEscapeShellArg( $params['physicalHeight'] ),
345 str_replace( '%w', wfEscapeShellArg( $params['physicalWidth'] ), $cmd ) ); # Size
346 wfDebug( __METHOD__
. ": Running custom convert command $cmd\n" );
348 $err = wfShellExecWithStderr( $cmd, $retval );
350 if ( $retval !== 0 ) {
351 $this->logErrorForExternalProcess( $retval, $err, $cmd );
353 return $this->getMediaTransformError( $params, $err );
356 return false; # No error
360 * Transform an image using the built in GD library
362 * @param File $image File associated with this thumbnail
363 * @param array $params Array with scaler params
365 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
367 protected function transformGd( $image, $params ) {
368 # Use PHP's builtin GD library functions.
369 # First find out what kind of file this is, and select the correct
370 # input routine for this.
373 'image/gif' => array( 'imagecreatefromgif', 'palette', false, 'imagegif' ),
374 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', true,
375 array( __CLASS__
, 'imageJpegWrapper' ) ),
376 'image/png' => array( 'imagecreatefrompng', 'bits', false, 'imagepng' ),
377 'image/vnd.wap.wbmp' => array( 'imagecreatefromwbmp', 'palette', false, 'imagewbmp' ),
378 'image/xbm' => array( 'imagecreatefromxbm', 'palette', false, 'imagexbm' ),
381 if ( !isset( $typemap[$params['mimeType']] ) ) {
382 $err = 'Image type not supported';
384 $errMsg = wfMessage( 'thumbnail_image-type' )->text();
386 return $this->getMediaTransformError( $params, $errMsg );
388 list( $loader, $colorStyle, $useQuality, $saveType ) = $typemap[$params['mimeType']];
390 if ( !function_exists( $loader ) ) {
391 $err = "Incomplete GD library configuration: missing function $loader";
393 $errMsg = wfMessage( 'thumbnail_gd-library', $loader )->text();
395 return $this->getMediaTransformError( $params, $errMsg );
398 if ( !file_exists( $params['srcPath'] ) ) {
399 $err = "File seems to be missing: {$params['srcPath']}";
401 $errMsg = wfMessage( 'thumbnail_image-missing', $params['srcPath'] )->text();
403 return $this->getMediaTransformError( $params, $errMsg );
406 $src_image = call_user_func( $loader, $params['srcPath'] );
408 $rotation = function_exists( 'imagerotate' ) && !isset( $params['disableRotation'] ) ?
409 $this->getRotation( $image ) :
411 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
412 $dst_image = imagecreatetruecolor( $width, $height );
414 // Initialise the destination image to transparent instead of
415 // the default solid black, to support PNG and GIF transparency nicely
416 $background = imagecolorallocate( $dst_image, 0, 0, 0 );
417 imagecolortransparent( $dst_image, $background );
418 imagealphablending( $dst_image, false );
420 if ( $colorStyle == 'palette' ) {
421 // Don't resample for paletted GIF images.
422 // It may just uglify them, and completely breaks transparency.
423 imagecopyresized( $dst_image, $src_image,
426 imagesx( $src_image ), imagesy( $src_image ) );
428 imagecopyresampled( $dst_image, $src_image,
431 imagesx( $src_image ), imagesy( $src_image ) );
434 if ( $rotation %
360 != 0 && $rotation %
90 == 0 ) {
435 $rot_image = imagerotate( $dst_image, $rotation, 0 );
436 imagedestroy( $dst_image );
437 $dst_image = $rot_image;
440 imagesavealpha( $dst_image, true );
442 $funcParams = array( $dst_image, $params['dstPath'] );
443 if ( $useQuality && isset( $params['quality'] ) ) {
444 $funcParams[] = $params['quality'];
446 call_user_func_array( $saveType, $funcParams );
448 imagedestroy( $dst_image );
449 imagedestroy( $src_image );
451 return false; # No error
455 * Callback for transformGd when transforming jpeg images.
457 // FIXME: transformImageMagick() & transformImageMagickExt() uses JPEG quality 80, here it's 95?
458 static function imageJpegWrapper( $dst_image, $thumbPath, $quality = 95 ) {
459 imageinterlace( $dst_image );
460 imagejpeg( $dst_image, $thumbPath, $quality );
464 * Returns whether the current scaler supports rotation (im and gd do)
468 public function canRotate() {
469 $scaler = $this->getScalerType( null, false );
472 # ImageMagick supports autorotation
475 # Imagick::rotateImage
478 # GD's imagerotate function is used to rotate images, but not
479 # all precompiled PHP versions have that function
480 return function_exists( 'imagerotate' );
482 # Other scalers don't support rotation
488 * @see $wgEnableAutoRotation
489 * @return bool Whether auto rotation is enabled
491 public function autoRotateEnabled() {
492 global $wgEnableAutoRotation;
494 if ( $wgEnableAutoRotation === null ) {
495 // Only enable auto-rotation when we actually can
496 return $this->canRotate();
499 return $wgEnableAutoRotation;
504 * @param array $params Rotate parameters.
505 * 'rotation' clockwise rotation in degrees, allowed are multiples of 90
509 public function rotate( $file, $params ) {
510 global $wgImageMagickConvertCommand;
512 $rotation = ( $params['rotation'] +
$this->getRotation( $file ) ) %
360;
515 $scaler = $this->getScalerType( null, false );
518 $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . " " .
519 wfEscapeShellArg( $this->escapeMagickInput( $params['srcPath'], $scene ) ) .
520 " -rotate " . wfEscapeShellArg( "-$rotation" ) . " " .
521 wfEscapeShellArg( $this->escapeMagickOutput( $params['dstPath'] ) );
522 wfDebug( __METHOD__
. ": running ImageMagick: $cmd\n" );
524 $err = wfShellExecWithStderr( $cmd, $retval );
525 if ( $retval !== 0 ) {
526 $this->logErrorForExternalProcess( $retval, $err, $cmd );
528 return new MediaTransformError( 'thumbnail_error', 0, 0, $err );
534 $im->readImage( $params['srcPath'] );
535 if ( !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) {
536 return new MediaTransformError( 'thumbnail_error', 0, 0,
537 "Error rotating $rotation degrees" );
539 $result = $im->writeImage( $params['dstPath'] );
541 return new MediaTransformError( 'thumbnail_error', 0, 0,
542 "Unable to write image to {$params['dstPath']}" );
547 return new MediaTransformError( 'thumbnail_error', 0, 0,
548 "$scaler rotation not implemented" );