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;
78 $animation_pre = array();
79 $animation_post = array();
80 $decoderHint = array();
81 if ( $params['mimeType'] == 'image/jpeg' ) {
82 $qualityVal = isset( $params['quality'] ) ?
(string)$params['quality'] : null;
83 $quality = array( '-quality', $qualityVal ?
: '80' ); // 80%
84 # Sharpening, see bug 6193
85 if ( ( $params['physicalWidth'] +
$params['physicalHeight'] )
86 / ( $params['srcWidth'] +
$params['srcHeight'] )
87 < $wgSharpenReductionThreshold
89 $sharpen = array( '-sharpen', $wgSharpenParameter );
91 if ( version_compare( $this->getMagickVersion(), "6.5.6" ) >= 0 ) {
92 // JPEG decoder hint to reduce memory, available since IM 6.5.6-2
93 $decoderHint = array( '-define', "jpeg:size={$params['physicalDimensions']}" );
95 } elseif ( $params['mimeType'] == 'image/png' ) {
96 $quality = array( '-quality', '95' ); // zlib 9, adaptive filtering
98 } elseif ( $params['mimeType'] == 'image/gif' ) {
99 if ( $this->getImageArea( $image ) > $wgMaxAnimatedGifArea ) {
100 // Extract initial frame only; we're so big it'll
101 // be a total drag. :P
103 } elseif ( $this->isAnimatedImage( $image ) ) {
104 // Coalesce is needed to scale animated GIFs properly (bug 1017).
105 $animation_pre = array( '-coalesce' );
106 // We optimize the output, but -optimize is broken,
107 // use optimizeTransparency instead (bug 11822)
108 if ( version_compare( $this->getMagickVersion(), "6.3.5" ) >= 0 ) {
109 $animation_post = array( '-fuzz', '5%', '-layers', 'optimizeTransparency' );
112 } elseif ( $params['mimeType'] == 'image/x-xcf' ) {
113 // Before merging layers, we need to set the background
114 // to be transparent to preserve alpha, as -layers merge
115 // merges all layers on to a canvas filled with the
116 // background colour. After merging we reset the background
117 // to be white for the default background colour setting
118 // in the PNG image (which is used in old IE)
119 $animation_pre = array(
120 '-background', 'transparent',
122 '-background', 'white',
124 wfSuppressWarnings();
125 $xcfMeta = unserialize( $image->getMetadata() );
128 && isset( $xcfMeta['colorType'] )
129 && $xcfMeta['colorType'] === 'greyscale-alpha'
130 && version_compare( $this->getMagickVersion(), "6.8.9-3" ) < 0
132 // bug 66323 - Greyscale images not rendered properly.
133 // So only take the "red" channel.
134 $channelOnly = array( '-channel', 'R', '-separate' );
135 $animation_pre = array_merge( $animation_pre, $channelOnly );
139 // Use one thread only, to avoid deadlock bugs on OOM
140 $env = array( 'OMP_NUM_THREADS' => 1 );
141 if ( strval( $wgImageMagickTempDir ) !== '' ) {
142 $env['MAGICK_TMPDIR'] = $wgImageMagickTempDir;
145 $rotation = isset( $params['disableRotation'] ) ?
0 : $this->getRotation( $image );
146 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
148 $cmd = call_user_func_array( 'wfEscapeShellArg', array_merge(
149 array( $wgImageMagickConvertCommand ),
151 // Specify white background color, will be used for transparent images
152 // in Internet Explorer/Windows instead of default black.
153 array( '-background', 'white' ),
155 array( $this->escapeMagickInput( $params['srcPath'], $scene ) ),
157 // For the -thumbnail option a "!" is needed to force exact size,
158 // or ImageMagick may decide your ratio is wrong and slice off
160 array( '-thumbnail', "{$width}x{$height}!" ),
161 // Add the source url as a comment to the thumb, but don't add the flag if there's no comment
162 ( $params['comment'] !== ''
163 ?
array( '-set', 'comment', $this->escapeMagickProperty( $params['comment'] ) )
165 array( '-depth', 8 ),
167 array( '-rotate', "-$rotation" ),
169 array( $this->escapeMagickOutput( $params['dstPath'] ) ) ) );
171 wfDebug( __METHOD__
. ": running ImageMagick: $cmd\n" );
173 $err = wfShellExecWithStderr( $cmd, $retval, $env );
175 if ( $retval !== 0 ) {
176 $this->logErrorForExternalProcess( $retval, $err, $cmd );
178 return $this->getMediaTransformError( $params, "$err\nError code: $retval" );
181 return false; # No error
185 * Transform an image using the Imagick PHP extension
187 * @param File $image File associated with this thumbnail
188 * @param array $params Array with scaler params
190 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
192 protected function transformImageMagickExt( $image, $params ) {
193 global $wgSharpenReductionThreshold, $wgSharpenParameter, $wgMaxAnimatedGifArea;
197 $im->readImage( $params['srcPath'] );
199 if ( $params['mimeType'] == 'image/jpeg' ) {
200 // Sharpening, see bug 6193
201 if ( ( $params['physicalWidth'] +
$params['physicalHeight'] )
202 / ( $params['srcWidth'] +
$params['srcHeight'] )
203 < $wgSharpenReductionThreshold
205 // Hack, since $wgSharpenParameter is written specifically for the command line convert
206 list( $radius, $sigma ) = explode( 'x', $wgSharpenParameter );
207 $im->sharpenImage( $radius, $sigma );
209 $qualityVal = isset( $params['quality'] ) ?
(string)$params['quality'] : null;
210 $im->setCompressionQuality( $qualityVal ?
: 80 );
211 } elseif ( $params['mimeType'] == 'image/png' ) {
212 $im->setCompressionQuality( 95 );
213 } elseif ( $params['mimeType'] == 'image/gif' ) {
214 if ( $this->getImageArea( $image ) > $wgMaxAnimatedGifArea ) {
215 // Extract initial frame only; we're so big it'll
216 // be a total drag. :P
217 $im->setImageScene( 0 );
218 } elseif ( $this->isAnimatedImage( $image ) ) {
219 // Coalesce is needed to scale animated GIFs properly (bug 1017).
220 $im = $im->coalesceImages();
224 $rotation = isset( $params['disableRotation'] ) ?
0 : $this->getRotation( $image );
225 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
227 $im->setImageBackgroundColor( new ImagickPixel( 'white' ) );
229 // Call Imagick::thumbnailImage on each frame
230 foreach ( $im as $i => $frame ) {
231 if ( !$frame->thumbnailImage( $width, $height, /* fit */ false ) ) {
232 return $this->getMediaTransformError( $params, "Error scaling frame $i" );
235 $im->setImageDepth( 8 );
238 if ( !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) {
239 return $this->getMediaTransformError( $params, "Error rotating $rotation degrees" );
243 if ( $this->isAnimatedImage( $image ) ) {
244 wfDebug( __METHOD__
. ": Writing animated thumbnail\n" );
245 // This is broken somehow... can't find out how to fix it
246 $result = $im->writeImages( $params['dstPath'], true );
248 $result = $im->writeImage( $params['dstPath'] );
251 return $this->getMediaTransformError( $params,
252 "Unable to write thumbnail to {$params['dstPath']}" );
254 } catch ( ImagickException
$e ) {
255 return $this->getMediaTransformError( $params, $e->getMessage() );
262 * Transform an image using a custom command
264 * @param File $image File associated with this thumbnail
265 * @param array $params Array with scaler params
267 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
269 protected function transformCustom( $image, $params ) {
270 # Use a custom convert command
271 global $wgCustomConvertCommand;
273 # Variables: %s %d %w %h
274 $src = wfEscapeShellArg( $params['srcPath'] );
275 $dst = wfEscapeShellArg( $params['dstPath'] );
276 $cmd = $wgCustomConvertCommand;
277 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
278 $cmd = str_replace( '%h', wfEscapeShellArg( $params['physicalHeight'] ),
279 str_replace( '%w', wfEscapeShellArg( $params['physicalWidth'] ), $cmd ) ); # Size
280 wfDebug( __METHOD__
. ": Running custom convert command $cmd\n" );
282 $err = wfShellExecWithStderr( $cmd, $retval );
284 if ( $retval !== 0 ) {
285 $this->logErrorForExternalProcess( $retval, $err, $cmd );
287 return $this->getMediaTransformError( $params, $err );
290 return false; # No error
294 * Transform an image using the built in GD library
296 * @param File $image File associated with this thumbnail
297 * @param array $params Array with scaler params
299 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
301 protected function transformGd( $image, $params ) {
302 # Use PHP's builtin GD library functions.
304 # First find out what kind of file this is, and select the correct
305 # input routine for this.
308 'image/gif' => array( 'imagecreatefromgif', 'palette', false, 'imagegif' ),
309 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', true,
310 array( __CLASS__
, 'imageJpegWrapper' ) ),
311 'image/png' => array( 'imagecreatefrompng', 'bits', false, 'imagepng' ),
312 'image/vnd.wap.wbmp' => array( 'imagecreatefromwbmp', 'palette', false, 'imagewbmp' ),
313 'image/xbm' => array( 'imagecreatefromxbm', 'palette', false, 'imagexbm' ),
316 if ( !isset( $typemap[$params['mimeType']] ) ) {
317 $err = 'Image type not supported';
319 $errMsg = wfMessage( 'thumbnail_image-type' )->text();
321 return $this->getMediaTransformError( $params, $errMsg );
323 list( $loader, $colorStyle, $useQuality, $saveType ) = $typemap[$params['mimeType']];
325 if ( !function_exists( $loader ) ) {
326 $err = "Incomplete GD library configuration: missing function $loader";
328 $errMsg = wfMessage( 'thumbnail_gd-library', $loader )->text();
330 return $this->getMediaTransformError( $params, $errMsg );
333 if ( !file_exists( $params['srcPath'] ) ) {
334 $err = "File seems to be missing: {$params['srcPath']}";
336 $errMsg = wfMessage( 'thumbnail_image-missing', $params['srcPath'] )->text();
338 return $this->getMediaTransformError( $params, $errMsg );
341 $src_image = call_user_func( $loader, $params['srcPath'] );
343 $rotation = function_exists( 'imagerotate' ) && !isset( $params['disableRotation'] ) ?
$this->getRotation( $image ) : 0;
344 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
345 $dst_image = imagecreatetruecolor( $width, $height );
347 // Initialise the destination image to transparent instead of
348 // the default solid black, to support PNG and GIF transparency nicely
349 $background = imagecolorallocate( $dst_image, 0, 0, 0 );
350 imagecolortransparent( $dst_image, $background );
351 imagealphablending( $dst_image, false );
353 if ( $colorStyle == 'palette' ) {
354 // Don't resample for paletted GIF images.
355 // It may just uglify them, and completely breaks transparency.
356 imagecopyresized( $dst_image, $src_image,
359 imagesx( $src_image ), imagesy( $src_image ) );
361 imagecopyresampled( $dst_image, $src_image,
364 imagesx( $src_image ), imagesy( $src_image ) );
367 if ( $rotation %
360 != 0 && $rotation %
90 == 0 ) {
368 $rot_image = imagerotate( $dst_image, $rotation, 0 );
369 imagedestroy( $dst_image );
370 $dst_image = $rot_image;
373 imagesavealpha( $dst_image, true );
375 $funcParams = array( $dst_image, $params['dstPath'] );
376 if ( $useQuality && isset( $params['quality'] ) ) {
377 $funcParams[] = $params['quality'];
379 call_user_func_array( $saveType, $funcParams );
381 imagedestroy( $dst_image );
382 imagedestroy( $src_image );
384 return false; # No error
388 * Callback for transformGd when transforming jpeg images.
390 // FIXME: transformImageMagick() & transformImageMagickExt() uses JPEG quality 80, here it's 95?
391 static function imageJpegWrapper( $dst_image, $thumbPath, $quality = 95 ) {
392 imageinterlace( $dst_image );
393 imagejpeg( $dst_image, $thumbPath, $quality );
397 * Returns whether the current scaler supports rotation (im and gd do)
401 public function canRotate() {
402 $scaler = $this->getScalerType( null, false );
405 # ImageMagick supports autorotation
408 # Imagick::rotateImage
411 # GD's imagerotate function is used to rotate images, but not
412 # all precompiled PHP versions have that function
413 return function_exists( 'imagerotate' );
415 # Other scalers don't support rotation
421 * @see $wgEnableAutoRotation
422 * @return bool Whether auto rotation is enabled
424 public function autoRotateEnabled() {
425 global $wgEnableAutoRotation;
427 if ( $wgEnableAutoRotation === null ) {
428 // Only enable auto-rotation when we actually can
429 return $this->canRotate();
432 return $wgEnableAutoRotation;
437 * @param array $params Rotate parameters.
438 * 'rotation' clockwise rotation in degrees, allowed are multiples of 90
442 public function rotate( $file, $params ) {
443 global $wgImageMagickConvertCommand;
445 $rotation = ( $params['rotation'] +
$this->getRotation( $file ) ) %
360;
448 $scaler = $this->getScalerType( null, false );
451 $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . " " .
452 wfEscapeShellArg( $this->escapeMagickInput( $params['srcPath'], $scene ) ) .
453 " -rotate " . wfEscapeShellArg( "-$rotation" ) . " " .
454 wfEscapeShellArg( $this->escapeMagickOutput( $params['dstPath'] ) );
455 wfDebug( __METHOD__
. ": running ImageMagick: $cmd\n" );
457 $err = wfShellExecWithStderr( $cmd, $retval );
458 if ( $retval !== 0 ) {
459 $this->logErrorForExternalProcess( $retval, $err, $cmd );
461 return new MediaTransformError( 'thumbnail_error', 0, 0, $err );
467 $im->readImage( $params['srcPath'] );
468 if ( !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) {
469 return new MediaTransformError( 'thumbnail_error', 0, 0,
470 "Error rotating $rotation degrees" );
472 $result = $im->writeImage( $params['dstPath'] );
474 return new MediaTransformError( 'thumbnail_error', 0, 0,
475 "Unable to write image to {$params['dstPath']}" );
480 return new MediaTransformError( 'thumbnail_error', 0, 0,
481 "$scaler rotation not implemented" );