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 ImageHandler
{
32 * @param array $params Transform parameters. Entries with the keys 'width'
33 * and 'height' are the respective screen width and height, while the keys
34 * 'physicalWidth' and 'physicalHeight' indicate the thumbnail dimensions.
37 function normaliseParams( $image, &$params ) {
38 if ( !parent
::normaliseParams( $image, $params ) ) {
42 # Obtain the source, pre-rotation dimensions
43 $srcWidth = $image->getWidth( $params['page'] );
44 $srcHeight = $image->getHeight( $params['page'] );
46 # Don't make an image bigger than the source
47 if ( $params['physicalWidth'] >= $srcWidth ) {
48 $params['physicalWidth'] = $srcWidth;
49 $params['physicalHeight'] = $srcHeight;
51 # Skip scaling limit checks if no scaling is required
52 # due to requested size being bigger than source.
53 if ( !$image->mustRender() ) {
58 # Check if the file is smaller than the maximum image area for thumbnailing
59 $checkImageAreaHookResult = null;
61 'BitmapHandlerCheckImageArea',
62 array( $image, &$params, &$checkImageAreaHookResult )
65 if ( is_null( $checkImageAreaHookResult ) ) {
66 global $wgMaxImageArea;
68 if ( $srcWidth * $srcHeight > $wgMaxImageArea
69 && !( $image->getMimeType() == 'image/jpeg'
70 && self
::getScalerType( false, false ) == 'im' )
72 # Only ImageMagick can efficiently downsize jpg images without loading
73 # the entire file in memory
77 return $checkImageAreaHookResult;
84 * Extracts the width/height if the image will be scaled before rotating
86 * This will match the physical size/aspect ratio of the original image
87 * prior to application of the rotation -- so for a portrait image that's
88 * stored as raw landscape with 90-degress rotation, the resulting size
89 * will be wider than it is tall.
91 * @param array $params Parameters as returned by normaliseParams
92 * @param int $rotation The rotation angle that will be applied
93 * @return array ($width, $height) array
95 public function extractPreRotationDimensions( $params, $rotation ) {
96 if ( $rotation == 90 ||
$rotation == 270 ) {
97 # We'll resize before rotation, so swap the dimensions again
98 $width = $params['physicalHeight'];
99 $height = $params['physicalWidth'];
101 $width = $params['physicalWidth'];
102 $height = $params['physicalHeight'];
105 return array( $width, $height );
110 * @param string $dstPath
111 * @param string $dstUrl
112 * @param array $params
114 * @return MediaTransformError|ThumbnailImage|TransformParameterError
116 function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
117 if ( !$this->normaliseParams( $image, $params ) ) {
118 return new TransformParameterError( $params );
120 # Create a parameter array to pass to the scaler
121 $scalerParams = array(
122 # The size to which the image will be resized
123 'physicalWidth' => $params['physicalWidth'],
124 'physicalHeight' => $params['physicalHeight'],
125 'physicalDimensions' => "{$params['physicalWidth']}x{$params['physicalHeight']}",
126 # The size of the image on the page
127 'clientWidth' => $params['width'],
128 'clientHeight' => $params['height'],
129 # Comment as will be added to the Exif of the thumbnail
130 'comment' => isset( $params['descriptionUrl'] )
131 ?
"File source: {$params['descriptionUrl']}"
133 # Properties of the original image
134 'srcWidth' => $image->getWidth(),
135 'srcHeight' => $image->getHeight(),
136 'mimeType' => $image->getMimeType(),
137 'dstPath' => $dstPath,
141 # Determine scaler type
142 $scaler = self
::getScalerType( $dstPath );
144 wfDebug( __METHOD__
. ": creating {$scalerParams['physicalDimensions']} " .
145 "thumbnail at $dstPath using scaler $scaler\n" );
147 if ( !$image->mustRender() &&
148 $scalerParams['physicalWidth'] == $scalerParams['srcWidth']
149 && $scalerParams['physicalHeight'] == $scalerParams['srcHeight']
152 # normaliseParams (or the user) wants us to return the unscaled image
153 wfDebug( __METHOD__
. ": returning unscaled image\n" );
155 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
158 if ( $scaler == 'client' ) {
159 # Client-side image scaling, use the source URL
160 # Using the destination URL in a TRANSFORM_LATER request would be incorrect
161 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
164 if ( $flags & self
::TRANSFORM_LATER
) {
165 wfDebug( __METHOD__
. ": Transforming later per flags.\n" );
167 'width' => $scalerParams['clientWidth'],
168 'height' => $scalerParams['clientHeight']
171 return new ThumbnailImage( $image, $dstUrl, false, $params );
174 # Try to make a target path for the thumbnail
175 if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__
) ) {
176 wfDebug( __METHOD__
. ": Unable to create thumbnail destination " .
177 "directory, falling back to client scaling\n" );
179 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
182 # Transform functions and binaries need a FS source file
183 $scalerParams['srcPath'] = $image->getLocalRefPath();
184 if ( $scalerParams['srcPath'] === false ) { // Failed to get local copy
185 wfDebugLog( 'thumbnail',
186 sprintf( 'Thumbnail failed on %s: could not get local copy of "%s"',
187 wfHostname(), $image->getName() ) );
189 return new MediaTransformError( 'thumbnail_error',
190 $scalerParams['clientWidth'], $scalerParams['clientHeight'],
191 wfMessage( 'filemissing' )->text()
197 wfRunHooks( 'BitmapHandlerTransform', array( $this, $image, &$scalerParams, &$mto ) );
198 if ( !is_null( $mto ) ) {
199 wfDebug( __METHOD__
. ": Hook to BitmapHandlerTransform created an mto\n" );
200 $scaler = 'hookaborted';
205 # Handled by the hook above
206 /** @var MediaTransformOutput $mto */
207 $err = $mto->isError() ?
$mto : false;
210 $err = $this->transformImageMagick( $image, $scalerParams );
213 $err = $this->transformCustom( $image, $scalerParams );
216 $err = $this->transformImageMagickExt( $image, $scalerParams );
220 $err = $this->transformGd( $image, $scalerParams );
224 # Remove the file if a zero-byte thumbnail was created, or if there was an error
225 $removed = $this->removeBadFile( $dstPath, (bool)$err );
227 # transform returned MediaTransforError
229 } elseif ( $removed ) {
230 # Thumbnail was zero-byte and had to be removed
231 return new MediaTransformError( 'thumbnail_error',
232 $scalerParams['clientWidth'], $scalerParams['clientHeight'],
233 wfMessage( 'unknown-error' )->text()
239 'width' => $scalerParams['clientWidth'],
240 'height' => $scalerParams['clientHeight']
243 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
248 * Returns which scaler type should be used. Creates parent directories
249 * for $dstPath and returns 'client' on error
251 * @param string $dstPath
252 * @param bool $checkDstPath
253 * @return string One of client, im, custom, gd, imext
255 protected static function getScalerType( $dstPath, $checkDstPath = true ) {
256 global $wgUseImageResize, $wgUseImageMagick, $wgCustomConvertCommand;
258 if ( !$dstPath && $checkDstPath ) {
259 # No output path available, client side scaling only
261 } elseif ( !$wgUseImageResize ) {
263 } elseif ( $wgUseImageMagick ) {
265 } elseif ( $wgCustomConvertCommand ) {
267 } elseif ( function_exists( 'imagecreatetruecolor' ) ) {
269 } elseif ( class_exists( 'Imagick' ) ) {
279 * Get a ThumbnailImage that respresents an image that will be scaled
282 * @param File $image File associated with this thumbnail
283 * @param array $scalerParams Array with scaler params
284 * @return ThumbnailImage
286 * @todo FIXME: No rotation support
288 protected function getClientScalingThumbnailImage( $image, $scalerParams ) {
290 'width' => $scalerParams['clientWidth'],
291 'height' => $scalerParams['clientHeight']
294 return new ThumbnailImage( $image, $image->getURL(), null, $params );
298 * Transform an image using ImageMagick
300 * @param File $image File associated with this thumbnail
301 * @param array $params Array with scaler params
303 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
305 protected function transformImageMagick( $image, $params ) {
307 global $wgSharpenReductionThreshold, $wgSharpenParameter, $wgMaxAnimatedGifArea,
308 $wgImageMagickTempDir, $wgImageMagickConvertCommand;
314 $animation_post = '';
316 if ( $params['mimeType'] == 'image/jpeg' ) {
317 $quality = "-quality 80"; // 80%
318 # Sharpening, see bug 6193
319 if ( ( $params['physicalWidth'] +
$params['physicalHeight'] )
320 / ( $params['srcWidth'] +
$params['srcHeight'] )
321 < $wgSharpenReductionThreshold
323 $sharpen = "-sharpen " . wfEscapeShellArg( $wgSharpenParameter );
325 if ( version_compare( $this->getMagickVersion(), "6.5.6" ) >= 0 ) {
326 // JPEG decoder hint to reduce memory, available since IM 6.5.6-2
327 $decoderHint = "-define jpeg:size={$params['physicalDimensions']}";
329 } elseif ( $params['mimeType'] == 'image/png' ) {
330 $quality = "-quality 95"; // zlib 9, adaptive filtering
332 } elseif ( $params['mimeType'] == 'image/gif' ) {
333 if ( $this->getImageArea( $image ) > $wgMaxAnimatedGifArea ) {
334 // Extract initial frame only; we're so big it'll
335 // be a total drag. :P
337 } elseif ( $this->isAnimatedImage( $image ) ) {
338 // Coalesce is needed to scale animated GIFs properly (bug 1017).
339 $animation_pre = '-coalesce';
340 // We optimize the output, but -optimize is broken,
341 // use optimizeTransparency instead (bug 11822)
342 if ( version_compare( $this->getMagickVersion(), "6.3.5" ) >= 0 ) {
343 $animation_post = '-fuzz 5% -layers optimizeTransparency';
346 } elseif ( $params['mimeType'] == 'image/x-xcf' ) {
347 $animation_post = '-layers merge';
350 // Use one thread only, to avoid deadlock bugs on OOM
351 $env = array( 'OMP_NUM_THREADS' => 1 );
352 if ( strval( $wgImageMagickTempDir ) !== '' ) {
353 $env['MAGICK_TMPDIR'] = $wgImageMagickTempDir;
356 $rotation = $this->getRotation( $image );
357 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
360 wfEscapeShellArg( $wgImageMagickConvertCommand ) .
361 // Specify white background color, will be used for transparent images
362 // in Internet Explorer/Windows instead of default black.
363 " {$quality} -background white" .
365 wfEscapeShellArg( $this->escapeMagickInput( $params['srcPath'], $scene ) ) .
366 " {$animation_pre}" .
367 // For the -thumbnail option a "!" is needed to force exact size,
368 // or ImageMagick may decide your ratio is wrong and slice off
370 " -thumbnail " . wfEscapeShellArg( "{$width}x{$height}!" ) .
371 // Add the source url as a comment to the thumb, but don't add the flag if there's no comment
372 ( $params['comment'] !== ''
373 ?
" -set comment " . wfEscapeShellArg( $this->escapeMagickProperty( $params['comment'] ) )
375 " -depth 8 $sharpen " .
376 " -rotate -$rotation " .
377 " {$animation_post} " .
378 wfEscapeShellArg( $this->escapeMagickOutput( $params['dstPath'] ) );
380 wfDebug( __METHOD__
. ": running ImageMagick: $cmd\n" );
381 wfProfileIn( 'convert' );
383 $err = wfShellExecWithStderr( $cmd, $retval, $env );
384 wfProfileOut( 'convert' );
386 if ( $retval !== 0 ) {
387 $this->logErrorForExternalProcess( $retval, $err, $cmd );
389 return $this->getMediaTransformError( $params, "$err\nError code: $retval" );
392 return false; # No error
396 * Transform an image using the Imagick PHP extension
398 * @param File $image File associated with this thumbnail
399 * @param array $params Array with scaler params
401 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
403 protected function transformImageMagickExt( $image, $params ) {
404 global $wgSharpenReductionThreshold, $wgSharpenParameter, $wgMaxAnimatedGifArea;
408 $im->readImage( $params['srcPath'] );
410 if ( $params['mimeType'] == 'image/jpeg' ) {
411 // Sharpening, see bug 6193
412 if ( ( $params['physicalWidth'] +
$params['physicalHeight'] )
413 / ( $params['srcWidth'] +
$params['srcHeight'] )
414 < $wgSharpenReductionThreshold
416 // Hack, since $wgSharpenParamater is written specifically for the command line convert
417 list( $radius, $sigma ) = explode( 'x', $wgSharpenParameter );
418 $im->sharpenImage( $radius, $sigma );
420 $im->setCompressionQuality( 80 );
421 } elseif ( $params['mimeType'] == 'image/png' ) {
422 $im->setCompressionQuality( 95 );
423 } elseif ( $params['mimeType'] == 'image/gif' ) {
424 if ( $this->getImageArea( $image ) > $wgMaxAnimatedGifArea ) {
425 // Extract initial frame only; we're so big it'll
426 // be a total drag. :P
427 $im->setImageScene( 0 );
428 } elseif ( $this->isAnimatedImage( $image ) ) {
429 // Coalesce is needed to scale animated GIFs properly (bug 1017).
430 $im = $im->coalesceImages();
434 $rotation = $this->getRotation( $image );
435 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
437 $im->setImageBackgroundColor( new ImagickPixel( 'white' ) );
439 // Call Imagick::thumbnailImage on each frame
440 foreach ( $im as $i => $frame ) {
441 if ( !$frame->thumbnailImage( $width, $height, /* fit */ false ) ) {
442 return $this->getMediaTransformError( $params, "Error scaling frame $i" );
445 $im->setImageDepth( 8 );
448 if ( !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) {
449 return $this->getMediaTransformError( $params, "Error rotating $rotation degrees" );
453 if ( $this->isAnimatedImage( $image ) ) {
454 wfDebug( __METHOD__
. ": Writing animated thumbnail\n" );
455 // This is broken somehow... can't find out how to fix it
456 $result = $im->writeImages( $params['dstPath'], true );
458 $result = $im->writeImage( $params['dstPath'] );
461 return $this->getMediaTransformError( $params,
462 "Unable to write thumbnail to {$params['dstPath']}" );
464 } catch ( ImagickException
$e ) {
465 return $this->getMediaTransformError( $params, $e->getMessage() );
472 * Transform an image using a custom command
474 * @param File $image File associated with this thumbnail
475 * @param array $params Array with scaler params
477 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
479 protected function transformCustom( $image, $params ) {
480 # Use a custom convert command
481 global $wgCustomConvertCommand;
483 # Variables: %s %d %w %h
484 $src = wfEscapeShellArg( $params['srcPath'] );
485 $dst = wfEscapeShellArg( $params['dstPath'] );
486 $cmd = $wgCustomConvertCommand;
487 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
488 $cmd = str_replace( '%h', $params['physicalHeight'],
489 str_replace( '%w', $params['physicalWidth'], $cmd ) ); # Size
490 wfDebug( __METHOD__
. ": Running custom convert command $cmd\n" );
491 wfProfileIn( 'convert' );
493 $err = wfShellExecWithStderr( $cmd, $retval );
494 wfProfileOut( 'convert' );
496 if ( $retval !== 0 ) {
497 $this->logErrorForExternalProcess( $retval, $err, $cmd );
499 return $this->getMediaTransformError( $params, $err );
502 return false; # No error
506 * Get a MediaTransformError with error 'thumbnail_error'
508 * @param array $params Parameter array as passed to the transform* functions
509 * @param string $errMsg Error message
510 * @return MediaTransformError
512 public function getMediaTransformError( $params, $errMsg ) {
513 return new MediaTransformError( 'thumbnail_error', $params['clientWidth'],
514 $params['clientHeight'], $errMsg );
518 * Transform an image using the built in GD library
520 * @param File $image File associated with this thumbnail
521 * @param array $params Array with scaler params
523 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
525 protected function transformGd( $image, $params ) {
526 # Use PHP's builtin GD library functions.
528 # First find out what kind of file this is, and select the correct
529 # input routine for this.
532 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
533 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor',
534 array( __CLASS__
, 'imageJpegWrapper' ) ),
535 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
536 'image/vnd.wap.wbmp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
537 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
539 if ( !isset( $typemap[$params['mimeType']] ) ) {
540 $err = 'Image type not supported';
542 $errMsg = wfMessage( 'thumbnail_image-type' )->text();
544 return $this->getMediaTransformError( $params, $errMsg );
546 list( $loader, $colorStyle, $saveType ) = $typemap[$params['mimeType']];
548 if ( !function_exists( $loader ) ) {
549 $err = "Incomplete GD library configuration: missing function $loader";
551 $errMsg = wfMessage( 'thumbnail_gd-library', $loader )->text();
553 return $this->getMediaTransformError( $params, $errMsg );
556 if ( !file_exists( $params['srcPath'] ) ) {
557 $err = "File seems to be missing: {$params['srcPath']}";
559 $errMsg = wfMessage( 'thumbnail_image-missing', $params['srcPath'] )->text();
561 return $this->getMediaTransformError( $params, $errMsg );
564 $src_image = call_user_func( $loader, $params['srcPath'] );
566 $rotation = function_exists( 'imagerotate' ) ?
$this->getRotation( $image ) : 0;
567 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
568 $dst_image = imagecreatetruecolor( $width, $height );
570 // Initialise the destination image to transparent instead of
571 // the default solid black, to support PNG and GIF transparency nicely
572 $background = imagecolorallocate( $dst_image, 0, 0, 0 );
573 imagecolortransparent( $dst_image, $background );
574 imagealphablending( $dst_image, false );
576 if ( $colorStyle == 'palette' ) {
577 // Don't resample for paletted GIF images.
578 // It may just uglify them, and completely breaks transparency.
579 imagecopyresized( $dst_image, $src_image,
582 imagesx( $src_image ), imagesy( $src_image ) );
584 imagecopyresampled( $dst_image, $src_image,
587 imagesx( $src_image ), imagesy( $src_image ) );
590 if ( $rotation %
360 != 0 && $rotation %
90 == 0 ) {
591 $rot_image = imagerotate( $dst_image, $rotation, 0 );
592 imagedestroy( $dst_image );
593 $dst_image = $rot_image;
596 imagesavealpha( $dst_image, true );
598 call_user_func( $saveType, $dst_image, $params['dstPath'] );
599 imagedestroy( $dst_image );
600 imagedestroy( $src_image );
602 return false; # No error
606 * Escape a string for ImageMagick's property input (e.g. -set -comment)
607 * See InterpretImageProperties() in magick/property.c
611 function escapeMagickProperty( $s ) {
612 // Double the backslashes
613 $s = str_replace( '\\', '\\\\', $s );
614 // Double the percents
615 $s = str_replace( '%', '%%', $s );
616 // Escape initial - or @
617 if ( strlen( $s ) > 0 && ( $s[0] === '-' ||
$s[0] === '@' ) ) {
625 * Escape a string for ImageMagick's input filenames. See ExpandFilenames()
626 * and GetPathComponent() in magick/utility.c.
628 * This won't work with an initial ~ or @, so input files should be prefixed
629 * with the directory name.
631 * Glob character unescaping is broken in ImageMagick before 6.6.1-5, but
632 * it's broken in a way that doesn't involve trying to convert every file
633 * in a directory, so we're better off escaping and waiting for the bugfix
634 * to filter down to users.
636 * @param string $path The file path
637 * @param bool|string $scene The scene specification, or false if there is none
638 * @throws MWException
641 function escapeMagickInput( $path, $scene = false ) {
642 # Die on initial metacharacters (caller should prepend path)
643 $firstChar = substr( $path, 0, 1 );
644 if ( $firstChar === '~' ||
$firstChar === '@' ) {
645 throw new MWException( __METHOD__
. ': cannot escape this path name' );
649 $path = preg_replace( '/[*?\[\]{}]/', '\\\\\0', $path );
651 return $this->escapeMagickPath( $path, $scene );
655 * Escape a string for ImageMagick's output filename. See
656 * InterpretImageFilename() in magick/image.c.
657 * @param string $path The file path
658 * @param bool|string $scene The scene specification, or false if there is none
661 function escapeMagickOutput( $path, $scene = false ) {
662 $path = str_replace( '%', '%%', $path );
664 return $this->escapeMagickPath( $path, $scene );
668 * Armour a string against ImageMagick's GetPathComponent(). This is a
669 * helper function for escapeMagickInput() and escapeMagickOutput().
671 * @param string $path The file path
672 * @param bool|string $scene The scene specification, or false if there is none
673 * @throws MWException
676 protected function escapeMagickPath( $path, $scene = false ) {
677 # Die on format specifiers (other than drive letters). The regex is
678 # meant to match all the formats you get from "convert -list format"
679 if ( preg_match( '/^([a-zA-Z0-9-]+):/', $path, $m ) ) {
680 if ( wfIsWindows() && is_dir( $m[0] ) ) {
681 // OK, it's a drive letter
682 // ImageMagick has a similar exception, see IsMagickConflict()
684 throw new MWException( __METHOD__
. ': unexpected colon character in path name' );
688 # If there are square brackets, add a do-nothing scene specification
689 # to force a literal interpretation
690 if ( $scene === false ) {
691 if ( strpos( $path, '[' ) !== false ) {
702 * Retrieve the version of the installed ImageMagick
703 * You can use PHPs version_compare() to use this value
704 * Value is cached for one hour.
705 * @return string Representing the IM version.
707 protected function getMagickVersion() {
710 $cache = $wgMemc->get( "imagemagick-version" );
712 global $wgImageMagickConvertCommand;
713 $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . ' -version';
714 wfDebug( __METHOD__
. ": Running convert -version\n" );
716 $return = wfShellExec( $cmd, $retval );
717 $x = preg_match( '/Version: ImageMagick ([0-9]*\.[0-9]*\.[0-9]*)/', $return, $matches );
719 wfDebug( __METHOD__
. ": ImageMagick version check failed\n" );
723 $wgMemc->set( "imagemagick-version", $matches[1], 3600 );
731 static function imageJpegWrapper( $dst_image, $thumbPath ) {
732 imageinterlace( $dst_image );
733 imagejpeg( $dst_image, $thumbPath, 95 );
737 * Returns whether the current scaler supports rotation (im and gd do)
741 public static function canRotate() {
742 $scaler = self
::getScalerType( null, false );
745 # ImageMagick supports autorotation
748 # Imagick::rotateImage
751 # GD's imagerotate function is used to rotate images, but not
752 # all precompiled PHP versions have that function
753 return function_exists( 'imagerotate' );
755 # Other scalers don't support rotation
761 * @see $wgEnableAutoRotation
762 * @return bool Whether auto rotation is enabled
764 public static function autoRotateEnabled() {
765 global $wgEnableAutoRotation;
767 if ( $wgEnableAutoRotation === null ) {
768 // Only enable auto-rotation when the bitmap handler can rotate
769 $wgEnableAutoRotation = BitmapHandler
::canRotate();
772 return $wgEnableAutoRotation;
777 * @param array $params Rotate parameters.
778 * 'rotation' clockwise rotation in degrees, allowed are multiples of 90
782 public function rotate( $file, $params ) {
783 global $wgImageMagickConvertCommand;
785 $rotation = ( $params['rotation'] +
$this->getRotation( $file ) ) %
360;
788 $scaler = self
::getScalerType( null, false );
791 $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . " " .
792 wfEscapeShellArg( $this->escapeMagickInput( $params['srcPath'], $scene ) ) .
793 " -rotate -$rotation " .
794 wfEscapeShellArg( $this->escapeMagickOutput( $params['dstPath'] ) );
795 wfDebug( __METHOD__
. ": running ImageMagick: $cmd\n" );
796 wfProfileIn( 'convert' );
798 // @todo FIXME: Undefined variable %env
799 $err = wfShellExecWithStderr( $cmd, $retval, $env );
800 wfProfileOut( 'convert' );
801 if ( $retval !== 0 ) {
802 $this->logErrorForExternalProcess( $retval, $err, $cmd );
804 return new MediaTransformError( 'thumbnail_error', 0, 0, $err );
810 $im->readImage( $params['srcPath'] );
811 if ( !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) {
812 return new MediaTransformError( 'thumbnail_error', 0, 0,
813 "Error rotating $rotation degrees" );
815 $result = $im->writeImage( $params['dstPath'] );
817 return new MediaTransformError( 'thumbnail_error', 0, 0,
818 "Unable to write image to {$params['dstPath']}" );
823 return new MediaTransformError( 'thumbnail_error', 0, 0,
824 "$scaler rotation not implemented" );
829 * Rerurns whether the file needs to be rendered. Returns true if the
830 * file requires rotation and we are able to rotate it.
835 public function mustRender( $file ) {
836 return self
::canRotate() && $this->getRotation( $file ) != 0;