Merge "Remove not used private member variable mParserWarnings from OutputPage"
[mediawiki.git] / includes / media / Bitmap.php
blobfaf40b3029b700efd617e605b1bb2045232c6724
1 <?php
2 /**
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
20 * @file
21 * @ingroup Media
24 /**
25 * Generic handler for bitmap images
27 * @ingroup Media
29 class BitmapHandler extends TransformationalImageHandler {
31 /**
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
44 $scaler = 'client';
45 } elseif ( !$wgUseImageResize ) {
46 $scaler = 'client';
47 } elseif ( $wgUseImageMagick ) {
48 $scaler = 'im';
49 } elseif ( $wgCustomConvertCommand ) {
50 $scaler = 'custom';
51 } elseif ( function_exists( 'imagecreatetruecolor' ) ) {
52 $scaler = 'gd';
53 } elseif ( class_exists( 'Imagick' ) ) {
54 $scaler = 'imext';
55 } else {
56 $scaler = 'client';
59 return $scaler;
62 /**
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 ) {
71 # use ImageMagick
72 global $wgSharpenReductionThreshold, $wgSharpenParameter, $wgMaxAnimatedGifArea,
73 $wgImageMagickTempDir, $wgImageMagickConvertCommand;
75 $quality = array();
76 $sharpen = array();
77 $scene = false;
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
88 ) {
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' || $params['mimeType'] == 'image/webp' ) {
96 $quality = array( '-quality', '95' ); // zlib 9, adaptive filtering
97 } elseif ( $params['mimeType'] == 'image/gif' ) {
98 if ( $this->getImageArea( $image ) > $wgMaxAnimatedGifArea ) {
99 // Extract initial frame only; we're so big it'll
100 // be a total drag. :P
101 $scene = 0;
102 } elseif ( $this->isAnimatedImage( $image ) ) {
103 // Coalesce is needed to scale animated GIFs properly (bug 1017).
104 $animation_pre = array( '-coalesce' );
105 // We optimize the output, but -optimize is broken,
106 // use optimizeTransparency instead (bug 11822)
107 if ( version_compare( $this->getMagickVersion(), "6.3.5" ) >= 0 ) {
108 $animation_post = array( '-fuzz', '5%', '-layers', 'optimizeTransparency' );
111 } elseif ( $params['mimeType'] == 'image/x-xcf' ) {
112 // Before merging layers, we need to set the background
113 // to be transparent to preserve alpha, as -layers merge
114 // merges all layers on to a canvas filled with the
115 // background colour. After merging we reset the background
116 // to be white for the default background colour setting
117 // in the PNG image (which is used in old IE)
118 $animation_pre = array(
119 '-background', 'transparent',
120 '-layers', 'merge',
121 '-background', 'white',
123 MediaWiki\suppressWarnings();
124 $xcfMeta = unserialize( $image->getMetadata() );
125 MediaWiki\restoreWarnings();
126 if ( $xcfMeta
127 && isset( $xcfMeta['colorType'] )
128 && $xcfMeta['colorType'] === 'greyscale-alpha'
129 && version_compare( $this->getMagickVersion(), "6.8.9-3" ) < 0
131 // bug 66323 - Greyscale images not rendered properly.
132 // So only take the "red" channel.
133 $channelOnly = array( '-channel', 'R', '-separate' );
134 $animation_pre = array_merge( $animation_pre, $channelOnly );
138 // Use one thread only, to avoid deadlock bugs on OOM
139 $env = array( 'OMP_NUM_THREADS' => 1 );
140 if ( strval( $wgImageMagickTempDir ) !== '' ) {
141 $env['MAGICK_TMPDIR'] = $wgImageMagickTempDir;
144 $rotation = isset( $params['disableRotation'] ) ? 0 : $this->getRotation( $image );
145 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
147 $cmd = call_user_func_array( 'wfEscapeShellArg', array_merge(
148 array( $wgImageMagickConvertCommand ),
149 $quality,
150 // Specify white background color, will be used for transparent images
151 // in Internet Explorer/Windows instead of default black.
152 array( '-background', 'white' ),
153 $decoderHint,
154 array( $this->escapeMagickInput( $params['srcPath'], $scene ) ),
155 $animation_pre,
156 // For the -thumbnail option a "!" is needed to force exact size,
157 // or ImageMagick may decide your ratio is wrong and slice off
158 // a pixel.
159 array( '-thumbnail', "{$width}x{$height}!" ),
160 // Add the source url as a comment to the thumb, but don't add the flag if there's no comment
161 ( $params['comment'] !== ''
162 ? array( '-set', 'comment', $this->escapeMagickProperty( $params['comment'] ) )
163 : array() ),
164 // T108616: Avoid exposure of local file path
165 array( '+set', 'Thumb::URI' ),
166 array( '-depth', 8 ),
167 $sharpen,
168 array( '-rotate', "-$rotation" ),
169 $animation_post,
170 array( $this->escapeMagickOutput( $params['dstPath'] ) ) ) );
172 wfDebug( __METHOD__ . ": running ImageMagick: $cmd\n" );
173 $retval = 0;
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;
196 try {
197 $im = new Imagick();
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 );
238 if ( $rotation ) {
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 );
248 } else {
249 $result = $im->writeImage( $params['dstPath'] );
251 if ( !$result ) {
252 return $this->getMediaTransformError( $params,
253 "Unable to write thumbnail to {$params['dstPath']}" );
255 } catch ( ImagickException $e ) {
256 return $this->getMediaTransformError( $params, $e->getMessage() );
259 return false;
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" );
282 $retval = 0;
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.
304 # First find out what kind of file this is, and select the correct
305 # input routine for this.
307 $typemap = array(
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';
318 wfDebug( "$err\n" );
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";
327 wfDebug( "$err\n" );
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']}";
335 wfDebug( "$err\n" );
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'] ) ?
344 $this->getRotation( $image ) :
346 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
347 $dst_image = imagecreatetruecolor( $width, $height );
349 // Initialise the destination image to transparent instead of
350 // the default solid black, to support PNG and GIF transparency nicely
351 $background = imagecolorallocate( $dst_image, 0, 0, 0 );
352 imagecolortransparent( $dst_image, $background );
353 imagealphablending( $dst_image, false );
355 if ( $colorStyle == 'palette' ) {
356 // Don't resample for paletted GIF images.
357 // It may just uglify them, and completely breaks transparency.
358 imagecopyresized( $dst_image, $src_image,
359 0, 0, 0, 0,
360 $width, $height,
361 imagesx( $src_image ), imagesy( $src_image ) );
362 } else {
363 imagecopyresampled( $dst_image, $src_image,
364 0, 0, 0, 0,
365 $width, $height,
366 imagesx( $src_image ), imagesy( $src_image ) );
369 if ( $rotation % 360 != 0 && $rotation % 90 == 0 ) {
370 $rot_image = imagerotate( $dst_image, $rotation, 0 );
371 imagedestroy( $dst_image );
372 $dst_image = $rot_image;
375 imagesavealpha( $dst_image, true );
377 $funcParams = array( $dst_image, $params['dstPath'] );
378 if ( $useQuality && isset( $params['quality'] ) ) {
379 $funcParams[] = $params['quality'];
381 call_user_func_array( $saveType, $funcParams );
383 imagedestroy( $dst_image );
384 imagedestroy( $src_image );
386 return false; # No error
390 * Callback for transformGd when transforming jpeg images.
392 // FIXME: transformImageMagick() & transformImageMagickExt() uses JPEG quality 80, here it's 95?
393 static function imageJpegWrapper( $dst_image, $thumbPath, $quality = 95 ) {
394 imageinterlace( $dst_image );
395 imagejpeg( $dst_image, $thumbPath, $quality );
399 * Returns whether the current scaler supports rotation (im and gd do)
401 * @return bool
403 public function canRotate() {
404 $scaler = $this->getScalerType( null, false );
405 switch ( $scaler ) {
406 case 'im':
407 # ImageMagick supports autorotation
408 return true;
409 case 'imext':
410 # Imagick::rotateImage
411 return true;
412 case 'gd':
413 # GD's imagerotate function is used to rotate images, but not
414 # all precompiled PHP versions have that function
415 return function_exists( 'imagerotate' );
416 default:
417 # Other scalers don't support rotation
418 return false;
423 * @see $wgEnableAutoRotation
424 * @return bool Whether auto rotation is enabled
426 public function autoRotateEnabled() {
427 global $wgEnableAutoRotation;
429 if ( $wgEnableAutoRotation === null ) {
430 // Only enable auto-rotation when we actually can
431 return $this->canRotate();
434 return $wgEnableAutoRotation;
438 * @param File $file
439 * @param array $params Rotate parameters.
440 * 'rotation' clockwise rotation in degrees, allowed are multiples of 90
441 * @since 1.21
442 * @return bool
444 public function rotate( $file, $params ) {
445 global $wgImageMagickConvertCommand;
447 $rotation = ( $params['rotation'] + $this->getRotation( $file ) ) % 360;
448 $scene = false;
450 $scaler = $this->getScalerType( null, false );
451 switch ( $scaler ) {
452 case 'im':
453 $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . " " .
454 wfEscapeShellArg( $this->escapeMagickInput( $params['srcPath'], $scene ) ) .
455 " -rotate " . wfEscapeShellArg( "-$rotation" ) . " " .
456 wfEscapeShellArg( $this->escapeMagickOutput( $params['dstPath'] ) );
457 wfDebug( __METHOD__ . ": running ImageMagick: $cmd\n" );
458 $retval = 0;
459 $err = wfShellExecWithStderr( $cmd, $retval );
460 if ( $retval !== 0 ) {
461 $this->logErrorForExternalProcess( $retval, $err, $cmd );
463 return new MediaTransformError( 'thumbnail_error', 0, 0, $err );
466 return false;
467 case 'imext':
468 $im = new Imagick();
469 $im->readImage( $params['srcPath'] );
470 if ( !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) {
471 return new MediaTransformError( 'thumbnail_error', 0, 0,
472 "Error rotating $rotation degrees" );
474 $result = $im->writeImage( $params['dstPath'] );
475 if ( !$result ) {
476 return new MediaTransformError( 'thumbnail_error', 0, 0,
477 "Unable to write image to {$params['dstPath']}" );
480 return false;
481 default:
482 return new MediaTransformError( 'thumbnail_error', 0, 0,
483 "$scaler rotation not implemented" );