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
24 use MediaWiki\Shell\Shell
;
27 * Generic handler for bitmap images
31 class BitmapHandler
extends TransformationalImageHandler
{
34 * Returns which scaler type should be used. Creates parent directories
35 * for $dstPath and returns 'client' on error
37 * @param string $dstPath
38 * @param bool $checkDstPath
39 * @return string|Callable One of client, im, custom, gd, imext or an array( object, method )
41 protected function getScalerType( $dstPath, $checkDstPath = true ) {
42 global $wgUseImageResize, $wgUseImageMagick, $wgCustomConvertCommand;
44 if ( !$dstPath && $checkDstPath ) {
45 # No output path available, client side scaling only
47 } elseif ( !$wgUseImageResize ) {
49 } elseif ( $wgUseImageMagick ) {
51 } elseif ( $wgCustomConvertCommand ) {
53 } elseif ( function_exists( 'imagecreatetruecolor' ) ) {
55 } elseif ( class_exists( 'Imagick' ) ) {
64 public function makeParamString( $params ) {
65 $res = parent
::makeParamString( $params );
66 if ( isset( $params['interlace'] ) && $params['interlace'] ) {
67 return "interlaced-{$res}";
73 public function parseParamString( $str ) {
74 $remainder = preg_replace( '/^interlaced-/', '', $str );
75 $params = parent
::parseParamString( $remainder );
76 if ( $params === false ) {
79 $params['interlace'] = $str !== $remainder;
83 public function validateParam( $name, $value ) {
84 if ( $name === 'interlace' ) {
85 return $value === false ||
$value === true;
87 return parent
::validateParam( $name, $value );
93 * @param array &$params
96 public function normaliseParams( $image, &$params ) {
97 global $wgMaxInterlacingAreas;
98 if ( !parent
::normaliseParams( $image, $params ) ) {
101 $mimeType = $image->getMimeType();
102 $interlace = isset( $params['interlace'] ) && $params['interlace']
103 && isset( $wgMaxInterlacingAreas[$mimeType] )
104 && $this->getImageArea( $image ) <= $wgMaxInterlacingAreas[$mimeType];
105 $params['interlace'] = $interlace;
110 * Get ImageMagick subsampling factors for the target JPEG pixel format.
112 * @param string $pixelFormat one of 'yuv444', 'yuv422', 'yuv420'
113 * @return array of string keys
115 protected function imageMagickSubsampling( $pixelFormat ) {
116 switch ( $pixelFormat ) {
118 return [ '1x1', '1x1', '1x1' ];
120 return [ '2x1', '1x1', '1x1' ];
122 return [ '2x2', '1x1', '1x1' ];
124 throw new MWException( 'Invalid pixel format for JPEG output' );
129 * Transform an image using ImageMagick
131 * @param File $image File associated with this thumbnail
132 * @param array $params Array with scaler params
134 * @return MediaTransformError|bool Error object if error occurred, false (=no error) otherwise
136 protected function transformImageMagick( $image, $params ) {
138 global $wgSharpenReductionThreshold, $wgSharpenParameter, $wgMaxAnimatedGifArea,
139 $wgImageMagickTempDir, $wgImageMagickConvertCommand, $wgJpegPixelFormat,
146 $animation_post = [];
150 if ( $params['mimeType'] == 'image/jpeg' ) {
151 $qualityVal = isset( $params['quality'] ) ?
(string)$params['quality'] : null;
152 $quality = [ '-quality', $qualityVal ?
: (string)$wgJpegQuality ]; // 80% by default
153 if ( $params['interlace'] ) {
154 $animation_post = [ '-interlace', 'JPEG' ];
156 # Sharpening, see T8193
157 if ( ( $params['physicalWidth'] +
$params['physicalHeight'] )
158 / ( $params['srcWidth'] +
$params['srcHeight'] )
159 < $wgSharpenReductionThreshold
161 $sharpen = [ '-sharpen', $wgSharpenParameter ];
163 if ( version_compare( $this->getMagickVersion(), "6.5.6" ) >= 0 ) {
164 // JPEG decoder hint to reduce memory, available since IM 6.5.6-2
165 $decoderHint = [ '-define', "jpeg:size={$params['physicalDimensions']}" ];
167 if ( $wgJpegPixelFormat ) {
168 $factors = $this->imageMagickSubsampling( $wgJpegPixelFormat );
169 $subsampling = [ '-sampling-factor', implode( ',', $factors ) ];
171 } elseif ( $params['mimeType'] == 'image/png' ) {
172 $quality = [ '-quality', '95' ]; // zlib 9, adaptive filtering
173 if ( $params['interlace'] ) {
174 $animation_post = [ '-interlace', 'PNG' ];
176 } elseif ( $params['mimeType'] == 'image/webp' ) {
177 $quality = [ '-quality', '95' ]; // zlib 9, adaptive filtering
178 } elseif ( $params['mimeType'] == 'image/gif' ) {
179 if ( $this->getImageArea( $image ) > $wgMaxAnimatedGifArea ) {
180 // Extract initial frame only; we're so big it'll
181 // be a total drag. :P
183 } elseif ( $this->isAnimatedImage( $image ) ) {
184 // Coalesce is needed to scale animated GIFs properly (T3017).
185 $animation_pre = [ '-coalesce' ];
186 // We optimize the output, but -optimize is broken,
187 // use optimizeTransparency instead (T13822)
188 if ( version_compare( $this->getMagickVersion(), "6.3.5" ) >= 0 ) {
189 $animation_post = [ '-fuzz', '5%', '-layers', 'optimizeTransparency' ];
192 if ( $params['interlace'] && version_compare( $this->getMagickVersion(), "6.3.4" ) >= 0
193 && !$this->isAnimatedImage( $image ) ) { // interlacing animated GIFs is a bad idea
194 $animation_post[] = '-interlace';
195 $animation_post[] = 'GIF';
197 } elseif ( $params['mimeType'] == 'image/x-xcf' ) {
198 // Before merging layers, we need to set the background
199 // to be transparent to preserve alpha, as -layers merge
200 // merges all layers on to a canvas filled with the
201 // background colour. After merging we reset the background
202 // to be white for the default background colour setting
203 // in the PNG image (which is used in old IE)
205 '-background', 'transparent',
207 '-background', 'white',
209 Wikimedia\
suppressWarnings();
210 $xcfMeta = unserialize( $image->getMetadata() );
211 Wikimedia\restoreWarnings
();
213 && isset( $xcfMeta['colorType'] )
214 && $xcfMeta['colorType'] === 'greyscale-alpha'
215 && version_compare( $this->getMagickVersion(), "6.8.9-3" ) < 0
217 // T68323 - Greyscale images not rendered properly.
218 // So only take the "red" channel.
219 $channelOnly = [ '-channel', 'R', '-separate' ];
220 $animation_pre = array_merge( $animation_pre, $channelOnly );
224 // Use one thread only, to avoid deadlock bugs on OOM
225 $env = [ 'OMP_NUM_THREADS' => 1 ];
226 if ( strval( $wgImageMagickTempDir ) !== '' ) {
227 $env['MAGICK_TMPDIR'] = $wgImageMagickTempDir;
230 $rotation = isset( $params['disableRotation'] ) ?
0 : $this->getRotation( $image );
231 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
233 $cmd = Shell
::escape( ...array_merge(
234 [ $wgImageMagickConvertCommand ],
236 // Specify white background color, will be used for transparent images
237 // in Internet Explorer/Windows instead of default black.
238 [ '-background', 'white' ],
240 [ $this->escapeMagickInput( $params['srcPath'], $scene ) ],
242 // For the -thumbnail option a "!" is needed to force exact size,
243 // or ImageMagick may decide your ratio is wrong and slice off
245 [ '-thumbnail', "{$width}x{$height}!" ],
246 // Add the source url as a comment to the thumb, but don't add the flag if there's no comment
247 ( $params['comment'] !== ''
248 ?
[ '-set', 'comment', $this->escapeMagickProperty( $params['comment'] ) ]
250 // T108616: Avoid exposure of local file path
251 [ '+set', 'Thumb::URI' ],
254 [ '-rotate', "-$rotation" ],
257 [ $this->escapeMagickOutput( $params['dstPath'] ) ] ) );
259 wfDebug( __METHOD__
. ": running ImageMagick: $cmd\n" );
261 $err = wfShellExecWithStderr( $cmd, $retval, $env );
263 if ( $retval !== 0 ) {
264 $this->logErrorForExternalProcess( $retval, $err, $cmd );
266 return $this->getMediaTransformError( $params, "$err\nError code: $retval" );
269 return false; # No error
273 * Transform an image using the Imagick PHP extension
275 * @param File $image File associated with this thumbnail
276 * @param array $params Array with scaler params
278 * @return MediaTransformError Error|bool object if error occurred, false (=no error) otherwise
280 protected function transformImageMagickExt( $image, $params ) {
281 global $wgSharpenReductionThreshold, $wgSharpenParameter, $wgMaxAnimatedGifArea,
282 $wgJpegPixelFormat, $wgJpegQuality;
286 $im->readImage( $params['srcPath'] );
288 if ( $params['mimeType'] == 'image/jpeg' ) {
289 // Sharpening, see T8193
290 if ( ( $params['physicalWidth'] +
$params['physicalHeight'] )
291 / ( $params['srcWidth'] +
$params['srcHeight'] )
292 < $wgSharpenReductionThreshold
294 // Hack, since $wgSharpenParameter is written specifically for the command line convert
295 list( $radius, $sigma ) = explode( 'x', $wgSharpenParameter );
296 $im->sharpenImage( $radius, $sigma );
298 $qualityVal = isset( $params['quality'] ) ?
(string)$params['quality'] : null;
299 $im->setCompressionQuality( $qualityVal ?
: $wgJpegQuality );
300 if ( $params['interlace'] ) {
301 $im->setInterlaceScheme( Imagick
::INTERLACE_JPEG
);
303 if ( $wgJpegPixelFormat ) {
304 $factors = $this->imageMagickSubsampling( $wgJpegPixelFormat );
305 $im->setSamplingFactors( $factors );
307 } elseif ( $params['mimeType'] == 'image/png' ) {
308 $im->setCompressionQuality( 95 );
309 if ( $params['interlace'] ) {
310 $im->setInterlaceScheme( Imagick
::INTERLACE_PNG
);
312 } elseif ( $params['mimeType'] == 'image/gif' ) {
313 if ( $this->getImageArea( $image ) > $wgMaxAnimatedGifArea ) {
314 // Extract initial frame only; we're so big it'll
315 // be a total drag. :P
316 $im->setImageScene( 0 );
317 } elseif ( $this->isAnimatedImage( $image ) ) {
318 // Coalesce is needed to scale animated GIFs properly (T3017).
319 $im = $im->coalesceImages();
321 // GIF interlacing is only available since 6.3.4
322 $v = Imagick
::getVersion();
323 preg_match( '/ImageMagick ([0-9]+\.[0-9]+\.[0-9]+)/', $v['versionString'], $v );
325 if ( $params['interlace'] && version_compare( $v[1], '6.3.4' ) >= 0 ) {
326 $im->setInterlaceScheme( Imagick
::INTERLACE_GIF
);
330 $rotation = isset( $params['disableRotation'] ) ?
0 : $this->getRotation( $image );
331 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
333 $im->setImageBackgroundColor( new ImagickPixel( 'white' ) );
335 // Call Imagick::thumbnailImage on each frame
336 foreach ( $im as $i => $frame ) {
337 if ( !$frame->thumbnailImage( $width, $height, /* fit */ false ) ) {
338 return $this->getMediaTransformError( $params, "Error scaling frame $i" );
341 $im->setImageDepth( 8 );
343 if ( $rotation && !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) {
344 return $this->getMediaTransformError( $params, "Error rotating $rotation degrees" );
347 if ( $this->isAnimatedImage( $image ) ) {
348 wfDebug( __METHOD__
. ": Writing animated thumbnail\n" );
349 // This is broken somehow... can't find out how to fix it
350 $result = $im->writeImages( $params['dstPath'], true );
352 $result = $im->writeImage( $params['dstPath'] );
355 return $this->getMediaTransformError( $params,
356 "Unable to write thumbnail to {$params['dstPath']}" );
358 } catch ( ImagickException
$e ) {
359 return $this->getMediaTransformError( $params, $e->getMessage() );
366 * Transform an image using a custom command
368 * @param File $image File associated with this thumbnail
369 * @param array $params Array with scaler params
371 * @return MediaTransformError Error|bool object if error occurred, false (=no error) otherwise
373 protected function transformCustom( $image, $params ) {
374 # Use a custom convert command
375 global $wgCustomConvertCommand;
377 # Variables: %s %d %w %h
378 $src = Shell
::escape( $params['srcPath'] );
379 $dst = Shell
::escape( $params['dstPath'] );
380 $cmd = $wgCustomConvertCommand;
381 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
382 $cmd = str_replace( '%h', Shell
::escape( $params['physicalHeight'] ),
383 str_replace( '%w', Shell
::escape( $params['physicalWidth'] ), $cmd ) ); # Size
384 wfDebug( __METHOD__
. ": Running custom convert command $cmd\n" );
386 $err = wfShellExecWithStderr( $cmd, $retval );
388 if ( $retval !== 0 ) {
389 $this->logErrorForExternalProcess( $retval, $err, $cmd );
391 return $this->getMediaTransformError( $params, $err );
394 return false; # No error
398 * Transform an image using the built in GD library
400 * @param File $image File associated with this thumbnail
401 * @param array $params Array with scaler params
403 * @return MediaTransformError|bool Error object if error occurred, false (=no error) otherwise
405 protected function transformGd( $image, $params ) {
406 # Use PHP's builtin GD library functions.
407 # First find out what kind of file this is, and select the correct
408 # input routine for this.
411 'image/gif' => [ 'imagecreatefromgif', 'palette', false, 'imagegif' ],
412 'image/jpeg' => [ 'imagecreatefromjpeg', 'truecolor', true,
413 [ __CLASS__
, 'imageJpegWrapper' ] ],
414 'image/png' => [ 'imagecreatefrompng', 'bits', false, 'imagepng' ],
415 'image/vnd.wap.wbmp' => [ 'imagecreatefromwbmp', 'palette', false, 'imagewbmp' ],
416 'image/xbm' => [ 'imagecreatefromxbm', 'palette', false, 'imagexbm' ],
419 if ( !isset( $typemap[$params['mimeType']] ) ) {
420 $err = 'Image type not supported';
422 $errMsg = wfMessage( 'thumbnail_image-type' )->text();
424 return $this->getMediaTransformError( $params, $errMsg );
426 list( $loader, $colorStyle, $useQuality, $saveType ) = $typemap[$params['mimeType']];
428 if ( !function_exists( $loader ) ) {
429 $err = "Incomplete GD library configuration: missing function $loader";
431 $errMsg = wfMessage( 'thumbnail_gd-library', $loader )->text();
433 return $this->getMediaTransformError( $params, $errMsg );
436 if ( !file_exists( $params['srcPath'] ) ) {
437 $err = "File seems to be missing: {$params['srcPath']}";
439 $errMsg = wfMessage( 'thumbnail_image-missing', $params['srcPath'] )->text();
441 return $this->getMediaTransformError( $params, $errMsg );
444 if ( filesize( $params['srcPath'] ) === 0 ) {
445 $err = "Image file size seems to be zero.";
447 $errMsg = wfMessage( 'thumbnail_image-size-zero', $params['srcPath'] )->text();
449 return $this->getMediaTransformError( $params, $errMsg );
452 $src_image = $loader( $params['srcPath'] );
454 $rotation = function_exists( 'imagerotate' ) && !isset( $params['disableRotation'] ) ?
455 $this->getRotation( $image ) :
457 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
458 $dst_image = imagecreatetruecolor( $width, $height );
460 // Initialise the destination image to transparent instead of
461 // the default solid black, to support PNG and GIF transparency nicely
462 $background = imagecolorallocate( $dst_image, 0, 0, 0 );
463 imagecolortransparent( $dst_image, $background );
464 imagealphablending( $dst_image, false );
466 if ( $colorStyle == 'palette' ) {
467 // Don't resample for paletted GIF images.
468 // It may just uglify them, and completely breaks transparency.
469 imagecopyresized( $dst_image, $src_image,
472 imagesx( $src_image ), imagesy( $src_image ) );
474 imagecopyresampled( $dst_image, $src_image,
477 imagesx( $src_image ), imagesy( $src_image ) );
480 if ( $rotation %
360 != 0 && $rotation %
90 == 0 ) {
481 $rot_image = imagerotate( $dst_image, $rotation, 0 );
482 imagedestroy( $dst_image );
483 $dst_image = $rot_image;
486 imagesavealpha( $dst_image, true );
488 $funcParams = [ $dst_image, $params['dstPath'] ];
489 if ( $useQuality && isset( $params['quality'] ) ) {
490 $funcParams[] = $params['quality'];
492 $saveType( ...$funcParams );
494 imagedestroy( $dst_image );
495 imagedestroy( $src_image );
497 return false; # No error
501 * Callback for transformGd when transforming jpeg images.
503 * @param resource $dst_image Image resource of the original image
504 * @param string $thumbPath File path to write the thumbnail image to
505 * @param int|null $quality Quality of the thumbnail from 1-100,
506 * or null to use default quality.
508 static function imageJpegWrapper( $dst_image, $thumbPath, $quality = null ) {
509 global $wgJpegQuality;
511 if ( $quality === null ) {
512 $quality = $wgJpegQuality;
515 imageinterlace( $dst_image );
516 imagejpeg( $dst_image, $thumbPath, $quality );
520 * Returns whether the current scaler supports rotation (im and gd do)
524 public function canRotate() {
525 $scaler = $this->getScalerType( null, false );
528 # ImageMagick supports autorotation
531 # Imagick::rotateImage
534 # GD's imagerotate function is used to rotate images, but not
535 # all precompiled PHP versions have that function
536 return function_exists( 'imagerotate' );
538 # Other scalers don't support rotation
544 * @see $wgEnableAutoRotation
545 * @return bool Whether auto rotation is enabled
547 public function autoRotateEnabled() {
548 global $wgEnableAutoRotation;
550 if ( $wgEnableAutoRotation === null ) {
551 // Only enable auto-rotation when we actually can
552 return $this->canRotate();
555 return $wgEnableAutoRotation;
560 * @param array $params Rotate parameters.
561 * 'rotation' clockwise rotation in degrees, allowed are multiples of 90
563 * @return bool|MediaTransformError
565 public function rotate( $file, $params ) {
566 global $wgImageMagickConvertCommand;
568 $rotation = ( $params['rotation'] +
$this->getRotation( $file ) ) %
360;
571 $scaler = $this->getScalerType( null, false );
574 $cmd = Shell
::escape( $wgImageMagickConvertCommand ) . " " .
575 Shell
::escape( $this->escapeMagickInput( $params['srcPath'], $scene ) ) .
576 " -rotate " . Shell
::escape( "-$rotation" ) . " " .
577 Shell
::escape( $this->escapeMagickOutput( $params['dstPath'] ) );
578 wfDebug( __METHOD__
. ": running ImageMagick: $cmd\n" );
580 $err = wfShellExecWithStderr( $cmd, $retval );
581 if ( $retval !== 0 ) {
582 $this->logErrorForExternalProcess( $retval, $err, $cmd );
584 return new MediaTransformError( 'thumbnail_error', 0, 0, $err );
590 $im->readImage( $params['srcPath'] );
591 if ( !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) {
592 return new MediaTransformError( 'thumbnail_error', 0, 0,
593 "Error rotating $rotation degrees" );
595 $result = $im->writeImage( $params['dstPath'] );
597 return new MediaTransformError( 'thumbnail_error', 0, 0,
598 "Unable to write image to {$params['dstPath']}" );
603 return new MediaTransformError( 'thumbnail_error', 0, 0,
604 "$scaler rotation not implemented" );