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' ) ) {
63 * Transform an image using ImageMagick
65 * @param File $image File associated with this thumbnail
66 * @param array $params Array with scaler params
68 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
70 protected function transformImageMagick( $image, $params ) {
72 global $wgSharpenReductionThreshold, $wgSharpenParameter, $wgMaxAnimatedGifArea,
73 $wgImageMagickTempDir, $wgImageMagickConvertCommand, $wgResourceBasePath,
74 $wgUseTinyRGBForJPGThumbnails;
79 $animation_pre = array();
80 $animation_post = array();
81 $decoderHint = array();
82 if ( $params['mimeType'] == 'image/jpeg' ) {
83 $qualityVal = isset( $params['quality'] ) ?
(string)$params['quality'] : null;
84 $quality = array( '-quality', $qualityVal ?
: '80' ); // 80%
85 # Sharpening, see bug 6193
86 if ( ( $params['physicalWidth'] +
$params['physicalHeight'] )
87 / ( $params['srcWidth'] +
$params['srcHeight'] )
88 < $wgSharpenReductionThreshold
90 $sharpen = array( '-sharpen', $wgSharpenParameter );
92 if ( version_compare( $this->getMagickVersion(), "6.5.6" ) >= 0 ) {
93 // JPEG decoder hint to reduce memory, available since IM 6.5.6-2
94 $decoderHint = array( '-define', "jpeg:size={$params['physicalDimensions']}" );
96 } elseif ( $params['mimeType'] == 'image/png' ) {
97 $quality = array( '-quality', '95' ); // zlib 9, adaptive filtering
99 } elseif ( $params['mimeType'] == 'image/gif' ) {
100 if ( $this->getImageArea( $image ) > $wgMaxAnimatedGifArea ) {
101 // Extract initial frame only; we're so big it'll
102 // be a total drag. :P
104 } elseif ( $this->isAnimatedImage( $image ) ) {
105 // Coalesce is needed to scale animated GIFs properly (bug 1017).
106 $animation_pre = array( '-coalesce' );
107 // We optimize the output, but -optimize is broken,
108 // use optimizeTransparency instead (bug 11822)
109 if ( version_compare( $this->getMagickVersion(), "6.3.5" ) >= 0 ) {
110 $animation_post = array( '-fuzz', '5%', '-layers', 'optimizeTransparency' );
113 } elseif ( $params['mimeType'] == 'image/x-xcf' ) {
114 // Before merging layers, we need to set the background
115 // to be transparent to preserve alpha, as -layers merge
116 // merges all layers on to a canvas filled with the
117 // background colour. After merging we reset the background
118 // to be white for the default background colour setting
119 // in the PNG image (which is used in old IE)
120 $animation_pre = array(
121 '-background', 'transparent',
123 '-background', 'white',
125 MediaWiki\
suppressWarnings();
126 $xcfMeta = unserialize( $image->getMetadata() );
127 MediaWiki\restoreWarnings
();
129 && isset( $xcfMeta['colorType'] )
130 && $xcfMeta['colorType'] === 'greyscale-alpha'
131 && version_compare( $this->getMagickVersion(), "6.8.9-3" ) < 0
133 // bug 66323 - Greyscale images not rendered properly.
134 // So only take the "red" channel.
135 $channelOnly = array( '-channel', 'R', '-separate' );
136 $animation_pre = array_merge( $animation_pre, $channelOnly );
140 // Use one thread only, to avoid deadlock bugs on OOM
141 $env = array( 'OMP_NUM_THREADS' => 1 );
142 if ( strval( $wgImageMagickTempDir ) !== '' ) {
143 $env['MAGICK_TMPDIR'] = $wgImageMagickTempDir;
146 $rotation = isset( $params['disableRotation'] ) ?
0 : $this->getRotation( $image );
147 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
149 $cmd = call_user_func_array( 'wfEscapeShellArg', array_merge(
150 array( $wgImageMagickConvertCommand ),
152 // Specify white background color, will be used for transparent images
153 // in Internet Explorer/Windows instead of default black.
154 array( '-background', 'white' ),
156 array( $this->escapeMagickInput( $params['srcPath'], $scene ) ),
158 // For the -thumbnail option a "!" is needed to force exact size,
159 // or ImageMagick may decide your ratio is wrong and slice off
161 array( '-thumbnail', "{$width}x{$height}!" ),
162 // Add the source url as a comment to the thumb, but don't add the flag if there's no comment
163 ( $params['comment'] !== ''
164 ?
array( '-set', 'comment', $this->escapeMagickProperty( $params['comment'] ) )
166 array( '-depth', 8 ),
168 array( '-rotate', "-$rotation" ),
170 array( $this->escapeMagickOutput( $params['dstPath'] ) ) ) );
172 wfDebug( __METHOD__
. ": running ImageMagick: $cmd\n" );
174 $err = wfShellExecWithStderr( $cmd, $retval, $env );
176 if ( $retval !== 0 ) {
177 $this->logErrorForExternalProcess( $retval, $err, $cmd );
179 return $this->getMediaTransformError( $params, "$err\nError code: $retval" );
182 return false; # No error
186 * Transform an image using the Imagick PHP extension
188 * @param File $image File associated with this thumbnail
189 * @param array $params Array with scaler params
191 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
193 protected function transformImageMagickExt( $image, $params ) {
194 global $wgSharpenReductionThreshold, $wgSharpenParameter, $wgMaxAnimatedGifArea;
198 $im->readImage( $params['srcPath'] );
200 if ( $params['mimeType'] == 'image/jpeg' ) {
201 // Sharpening, see bug 6193
202 if ( ( $params['physicalWidth'] +
$params['physicalHeight'] )
203 / ( $params['srcWidth'] +
$params['srcHeight'] )
204 < $wgSharpenReductionThreshold
206 // Hack, since $wgSharpenParameter is written specifically for the command line convert
207 list( $radius, $sigma ) = explode( 'x', $wgSharpenParameter );
208 $im->sharpenImage( $radius, $sigma );
210 $qualityVal = isset( $params['quality'] ) ?
(string)$params['quality'] : null;
211 $im->setCompressionQuality( $qualityVal ?
: 80 );
212 } elseif ( $params['mimeType'] == 'image/png' ) {
213 $im->setCompressionQuality( 95 );
214 } elseif ( $params['mimeType'] == 'image/gif' ) {
215 if ( $this->getImageArea( $image ) > $wgMaxAnimatedGifArea ) {
216 // Extract initial frame only; we're so big it'll
217 // be a total drag. :P
218 $im->setImageScene( 0 );
219 } elseif ( $this->isAnimatedImage( $image ) ) {
220 // Coalesce is needed to scale animated GIFs properly (bug 1017).
221 $im = $im->coalesceImages();
225 $rotation = isset( $params['disableRotation'] ) ?
0 : $this->getRotation( $image );
226 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
228 $im->setImageBackgroundColor( new ImagickPixel( 'white' ) );
230 // Call Imagick::thumbnailImage on each frame
231 foreach ( $im as $i => $frame ) {
232 if ( !$frame->thumbnailImage( $width, $height, /* fit */ false ) ) {
233 return $this->getMediaTransformError( $params, "Error scaling frame $i" );
236 $im->setImageDepth( 8 );
239 if ( !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) {
240 return $this->getMediaTransformError( $params, "Error rotating $rotation degrees" );
244 if ( $this->isAnimatedImage( $image ) ) {
245 wfDebug( __METHOD__
. ": Writing animated thumbnail\n" );
246 // This is broken somehow... can't find out how to fix it
247 $result = $im->writeImages( $params['dstPath'], true );
249 $result = $im->writeImage( $params['dstPath'] );
252 return $this->getMediaTransformError( $params,
253 "Unable to write thumbnail to {$params['dstPath']}" );
255 } catch ( ImagickException
$e ) {
256 return $this->getMediaTransformError( $params, $e->getMessage() );
263 * Transform an image using a custom command
265 * @param File $image File associated with this thumbnail
266 * @param array $params Array with scaler params
268 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
270 protected function transformCustom( $image, $params ) {
271 # Use a custom convert command
272 global $wgCustomConvertCommand;
274 # Variables: %s %d %w %h
275 $src = wfEscapeShellArg( $params['srcPath'] );
276 $dst = wfEscapeShellArg( $params['dstPath'] );
277 $cmd = $wgCustomConvertCommand;
278 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
279 $cmd = str_replace( '%h', wfEscapeShellArg( $params['physicalHeight'] ),
280 str_replace( '%w', wfEscapeShellArg( $params['physicalWidth'] ), $cmd ) ); # Size
281 wfDebug( __METHOD__
. ": Running custom convert command $cmd\n" );
283 $err = wfShellExecWithStderr( $cmd, $retval );
285 if ( $retval !== 0 ) {
286 $this->logErrorForExternalProcess( $retval, $err, $cmd );
288 return $this->getMediaTransformError( $params, $err );
291 return false; # No error
295 * Transform an image using the built in GD library
297 * @param File $image File associated with this thumbnail
298 * @param array $params Array with scaler params
300 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
302 protected function transformGd( $image, $params ) {
303 # Use PHP's builtin GD library functions.
305 # First find out what kind of file this is, and select the correct
306 # input routine for this.
309 'image/gif' => array( 'imagecreatefromgif', 'palette', false, 'imagegif' ),
310 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', true,
311 array( __CLASS__
, 'imageJpegWrapper' ) ),
312 'image/png' => array( 'imagecreatefrompng', 'bits', false, 'imagepng' ),
313 'image/vnd.wap.wbmp' => array( 'imagecreatefromwbmp', 'palette', false, 'imagewbmp' ),
314 'image/xbm' => array( 'imagecreatefromxbm', 'palette', false, 'imagexbm' ),
317 if ( !isset( $typemap[$params['mimeType']] ) ) {
318 $err = 'Image type not supported';
320 $errMsg = wfMessage( 'thumbnail_image-type' )->text();
322 return $this->getMediaTransformError( $params, $errMsg );
324 list( $loader, $colorStyle, $useQuality, $saveType ) = $typemap[$params['mimeType']];
326 if ( !function_exists( $loader ) ) {
327 $err = "Incomplete GD library configuration: missing function $loader";
329 $errMsg = wfMessage( 'thumbnail_gd-library', $loader )->text();
331 return $this->getMediaTransformError( $params, $errMsg );
334 if ( !file_exists( $params['srcPath'] ) ) {
335 $err = "File seems to be missing: {$params['srcPath']}";
337 $errMsg = wfMessage( 'thumbnail_image-missing', $params['srcPath'] )->text();
339 return $this->getMediaTransformError( $params, $errMsg );
342 $src_image = call_user_func( $loader, $params['srcPath'] );
344 $rotation = function_exists( 'imagerotate' ) && !isset( $params['disableRotation'] ) ?
$this->getRotation( $image ) : 0;
345 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
346 $dst_image = imagecreatetruecolor( $width, $height );
348 // Initialise the destination image to transparent instead of
349 // the default solid black, to support PNG and GIF transparency nicely
350 $background = imagecolorallocate( $dst_image, 0, 0, 0 );
351 imagecolortransparent( $dst_image, $background );
352 imagealphablending( $dst_image, false );
354 if ( $colorStyle == 'palette' ) {
355 // Don't resample for paletted GIF images.
356 // It may just uglify them, and completely breaks transparency.
357 imagecopyresized( $dst_image, $src_image,
360 imagesx( $src_image ), imagesy( $src_image ) );
362 imagecopyresampled( $dst_image, $src_image,
365 imagesx( $src_image ), imagesy( $src_image ) );
368 if ( $rotation %
360 != 0 && $rotation %
90 == 0 ) {
369 $rot_image = imagerotate( $dst_image, $rotation, 0 );
370 imagedestroy( $dst_image );
371 $dst_image = $rot_image;
374 imagesavealpha( $dst_image, true );
376 $funcParams = array( $dst_image, $params['dstPath'] );
377 if ( $useQuality && isset( $params['quality'] ) ) {
378 $funcParams[] = $params['quality'];
380 call_user_func_array( $saveType, $funcParams );
382 imagedestroy( $dst_image );
383 imagedestroy( $src_image );
385 return false; # No error
389 * Callback for transformGd when transforming jpeg images.
391 // FIXME: transformImageMagick() & transformImageMagickExt() uses JPEG quality 80, here it's 95?
392 static function imageJpegWrapper( $dst_image, $thumbPath, $quality = 95 ) {
393 imageinterlace( $dst_image );
394 imagejpeg( $dst_image, $thumbPath, $quality );
398 * Returns whether the current scaler supports rotation (im and gd do)
402 public function canRotate() {
403 $scaler = $this->getScalerType( null, false );
406 # ImageMagick supports autorotation
409 # Imagick::rotateImage
412 # GD's imagerotate function is used to rotate images, but not
413 # all precompiled PHP versions have that function
414 return function_exists( 'imagerotate' );
416 # Other scalers don't support rotation
422 * @see $wgEnableAutoRotation
423 * @return bool Whether auto rotation is enabled
425 public function autoRotateEnabled() {
426 global $wgEnableAutoRotation;
428 if ( $wgEnableAutoRotation === null ) {
429 // Only enable auto-rotation when we actually can
430 return $this->canRotate();
433 return $wgEnableAutoRotation;
438 * @param array $params Rotate parameters.
439 * 'rotation' clockwise rotation in degrees, allowed are multiples of 90
443 public function rotate( $file, $params ) {
444 global $wgImageMagickConvertCommand;
446 $rotation = ( $params['rotation'] +
$this->getRotation( $file ) ) %
360;
449 $scaler = $this->getScalerType( null, false );
452 $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . " " .
453 wfEscapeShellArg( $this->escapeMagickInput( $params['srcPath'], $scene ) ) .
454 " -rotate " . wfEscapeShellArg( "-$rotation" ) . " " .
455 wfEscapeShellArg( $this->escapeMagickOutput( $params['dstPath'] ) );
456 wfDebug( __METHOD__
. ": running ImageMagick: $cmd\n" );
458 $err = wfShellExecWithStderr( $cmd, $retval );
459 if ( $retval !== 0 ) {
460 $this->logErrorForExternalProcess( $retval, $err, $cmd );
462 return new MediaTransformError( 'thumbnail_error', 0, 0, $err );
468 $im->readImage( $params['srcPath'] );
469 if ( !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) {
470 return new MediaTransformError( 'thumbnail_error', 0, 0,
471 "Error rotating $rotation degrees" );
473 $result = $im->writeImage( $params['dstPath'] );
475 return new MediaTransformError( 'thumbnail_error', 0, 0,
476 "Unable to write image to {$params['dstPath']}" );
481 return new MediaTransformError( 'thumbnail_error', 0, 0,
482 "$scaler rotation not implemented" );