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;
60 wfRunHooks( 'BitmapHandlerCheckImageArea', array( $image, &$params, &$checkImageAreaHookResult ) );
61 if ( is_null( $checkImageAreaHookResult ) ) {
62 global $wgMaxImageArea;
64 if ( $srcWidth * $srcHeight > $wgMaxImageArea &&
65 !( $image->getMimeType() == 'image/jpeg' &&
66 self
::getScalerType( false, false ) == 'im' ) ) {
67 # Only ImageMagick can efficiently downsize jpg images without loading
68 # the entire file in memory
72 return $checkImageAreaHookResult;
79 * Extracts the width/height if the image will be scaled before rotating
81 * This will match the physical size/aspect ratio of the original image
82 * prior to application of the rotation -- so for a portrait image that's
83 * stored as raw landscape with 90-degress rotation, the resulting size
84 * will be wider than it is tall.
86 * @param array $params Parameters as returned by normaliseParams
87 * @param int $rotation The rotation angle that will be applied
88 * @return array ($width, $height) array
90 public function extractPreRotationDimensions( $params, $rotation ) {
91 if ( $rotation == 90 ||
$rotation == 270 ) {
92 # We'll resize before rotation, so swap the dimensions again
93 $width = $params['physicalHeight'];
94 $height = $params['physicalWidth'];
96 $width = $params['physicalWidth'];
97 $height = $params['physicalHeight'];
99 return array( $width, $height );
108 * @return MediaTransformError|ThumbnailImage|TransformParameterError
110 function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
111 if ( !$this->normaliseParams( $image, $params ) ) {
112 return new TransformParameterError( $params );
114 # Create a parameter array to pass to the scaler
115 $scalerParams = array(
116 # The size to which the image will be resized
117 'physicalWidth' => $params['physicalWidth'],
118 'physicalHeight' => $params['physicalHeight'],
119 'physicalDimensions' => "{$params['physicalWidth']}x{$params['physicalHeight']}",
120 # The size of the image on the page
121 'clientWidth' => $params['width'],
122 'clientHeight' => $params['height'],
123 # Comment as will be added to the Exif of the thumbnail
124 'comment' => isset( $params['descriptionUrl'] ) ?
125 "File source: {$params['descriptionUrl']}" : '',
126 # Properties of the original image
127 'srcWidth' => $image->getWidth(),
128 'srcHeight' => $image->getHeight(),
129 'mimeType' => $image->getMimeType(),
130 'dstPath' => $dstPath,
134 # Determine scaler type
135 $scaler = self
::getScalerType( $dstPath );
137 wfDebug( __METHOD__
. ": creating {$scalerParams['physicalDimensions']} thumbnail at $dstPath using scaler $scaler\n" );
139 if ( !$image->mustRender() &&
140 $scalerParams['physicalWidth'] == $scalerParams['srcWidth']
141 && $scalerParams['physicalHeight'] == $scalerParams['srcHeight'] ) {
143 # normaliseParams (or the user) wants us to return the unscaled image
144 wfDebug( __METHOD__
. ": returning unscaled image\n" );
145 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
148 if ( $scaler == 'client' ) {
149 # Client-side image scaling, use the source URL
150 # Using the destination URL in a TRANSFORM_LATER request would be incorrect
151 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
154 if ( $flags & self
::TRANSFORM_LATER
) {
155 wfDebug( __METHOD__
. ": Transforming later per flags.\n" );
157 'width' => $scalerParams['clientWidth'],
158 'height' => $scalerParams['clientHeight']
160 return new ThumbnailImage( $image, $dstUrl, false, $params );
163 # Try to make a target path for the thumbnail
164 if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__
) ) {
165 wfDebug( __METHOD__
. ": Unable to create thumbnail destination directory, falling back to client scaling\n" );
166 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
169 # Transform functions and binaries need a FS source file
170 $scalerParams['srcPath'] = $image->getLocalRefPath();
171 if ( $scalerParams['srcPath'] === false ) { // Failed to get local copy
172 wfDebugLog( 'thumbnail',
173 sprintf( 'Thumbnail failed on %s: could not get local copy of "%s"',
174 wfHostname(), $image->getName() ) );
175 return new MediaTransformError( 'thumbnail_error',
176 $scalerParams['clientWidth'], $scalerParams['clientHeight'] );
181 wfRunHooks( 'BitmapHandlerTransform', array( $this, $image, &$scalerParams, &$mto ) );
182 if ( !is_null( $mto ) ) {
183 wfDebug( __METHOD__
. ": Hook to BitmapHandlerTransform created an mto\n" );
184 $scaler = 'hookaborted';
189 # Handled by the hook above
190 $err = $mto->isError() ?
$mto : false;
193 $err = $this->transformImageMagick( $image, $scalerParams );
196 $err = $this->transformCustom( $image, $scalerParams );
199 $err = $this->transformImageMagickExt( $image, $scalerParams );
203 $err = $this->transformGd( $image, $scalerParams );
207 # Remove the file if a zero-byte thumbnail was created, or if there was an error
208 $removed = $this->removeBadFile( $dstPath, (bool)$err );
210 # transform returned MediaTransforError
212 } elseif ( $removed ) {
213 # Thumbnail was zero-byte and had to be removed
214 return new MediaTransformError( 'thumbnail_error',
215 $scalerParams['clientWidth'], $scalerParams['clientHeight'] );
220 'width' => $scalerParams['clientWidth'],
221 'height' => $scalerParams['clientHeight']
223 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
228 * Returns which scaler type should be used. Creates parent directories
229 * for $dstPath and returns 'client' on error
231 * @return string client,im,custom,gd
233 protected static function getScalerType( $dstPath, $checkDstPath = true ) {
234 global $wgUseImageResize, $wgUseImageMagick, $wgCustomConvertCommand;
236 if ( !$dstPath && $checkDstPath ) {
237 # No output path available, client side scaling only
239 } elseif ( !$wgUseImageResize ) {
241 } elseif ( $wgUseImageMagick ) {
243 } elseif ( $wgCustomConvertCommand ) {
245 } elseif ( function_exists( 'imagecreatetruecolor' ) ) {
247 } elseif ( class_exists( 'Imagick' ) ) {
256 * Get a ThumbnailImage that respresents an image that will be scaled
259 * @param $image File File associated with this thumbnail
260 * @param array $scalerParams Array with scaler params
261 * @return ThumbnailImage
263 * @todo fixme: no rotation support
265 protected function getClientScalingThumbnailImage( $image, $scalerParams ) {
267 'width' => $scalerParams['clientWidth'],
268 'height' => $scalerParams['clientHeight']
270 return new ThumbnailImage( $image, $image->getURL(), null, $params );
274 * Transform an image using ImageMagick
276 * @param $image File File associated with this thumbnail
277 * @param array $params Array with scaler params
279 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
281 protected function transformImageMagick( $image, $params ) {
283 global $wgSharpenReductionThreshold, $wgSharpenParameter,
284 $wgMaxAnimatedGifArea,
285 $wgImageMagickTempDir, $wgImageMagickConvertCommand;
291 $animation_post = '';
293 if ( $params['mimeType'] == 'image/jpeg' ) {
294 $quality = "-quality 80"; // 80%
295 # Sharpening, see bug 6193
296 if ( ( $params['physicalWidth'] +
$params['physicalHeight'] )
297 / ( $params['srcWidth'] +
$params['srcHeight'] )
298 < $wgSharpenReductionThreshold ) {
299 $sharpen = "-sharpen " . wfEscapeShellArg( $wgSharpenParameter );
301 if ( version_compare( $this->getMagickVersion(), "6.5.6" ) >= 0 ) {
302 // JPEG decoder hint to reduce memory, available since IM 6.5.6-2
303 $decoderHint = "-define jpeg:size={$params['physicalDimensions']}";
306 } elseif ( $params['mimeType'] == 'image/png' ) {
307 $quality = "-quality 95"; // zlib 9, adaptive filtering
309 } elseif ( $params['mimeType'] == 'image/gif' ) {
310 if ( $this->getImageArea( $image ) > $wgMaxAnimatedGifArea ) {
311 // Extract initial frame only; we're so big it'll
312 // be a total drag. :P
315 } elseif ( $this->isAnimatedImage( $image ) ) {
316 // Coalesce is needed to scale animated GIFs properly (bug 1017).
317 $animation_pre = '-coalesce';
318 // We optimize the output, but -optimize is broken,
319 // use optimizeTransparency instead (bug 11822)
320 if ( version_compare( $this->getMagickVersion(), "6.3.5" ) >= 0 ) {
321 $animation_post = '-fuzz 5% -layers optimizeTransparency';
324 } elseif ( $params['mimeType'] == 'image/x-xcf' ) {
325 $animation_post = '-layers merge';
328 // Use one thread only, to avoid deadlock bugs on OOM
329 $env = array( 'OMP_NUM_THREADS' => 1 );
330 if ( strval( $wgImageMagickTempDir ) !== '' ) {
331 $env['MAGICK_TMPDIR'] = $wgImageMagickTempDir;
334 $rotation = $this->getRotation( $image );
335 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
338 wfEscapeShellArg( $wgImageMagickConvertCommand ) .
339 // Specify white background color, will be used for transparent images
340 // in Internet Explorer/Windows instead of default black.
341 " {$quality} -background white" .
343 wfEscapeShellArg( $this->escapeMagickInput( $params['srcPath'], $scene ) ) .
344 " {$animation_pre}" .
345 // For the -thumbnail option a "!" is needed to force exact size,
346 // or ImageMagick may decide your ratio is wrong and slice off
348 " -thumbnail " . wfEscapeShellArg( "{$width}x{$height}!" ) .
349 // Add the source url as a comment to the thumb, but don't add the flag if there's no comment
350 ( $params['comment'] !== ''
351 ?
" -set comment " . wfEscapeShellArg( $this->escapeMagickProperty( $params['comment'] ) )
353 " -depth 8 $sharpen " .
354 " -rotate -$rotation " .
355 " {$animation_post} " .
356 wfEscapeShellArg( $this->escapeMagickOutput( $params['dstPath'] ) );
358 wfDebug( __METHOD__
. ": running ImageMagick: $cmd\n" );
359 wfProfileIn( 'convert' );
361 $err = wfShellExecWithStderr( $cmd, $retval, $env );
362 wfProfileOut( 'convert' );
364 if ( $retval !== 0 ) {
365 $this->logErrorForExternalProcess( $retval, $err, $cmd );
366 return $this->getMediaTransformError( $params, $err );
369 return false; # No error
373 * Transform an image using the Imagick PHP extension
375 * @param $image File File associated with this thumbnail
376 * @param array $params Array with scaler params
378 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
380 protected function transformImageMagickExt( $image, $params ) {
381 global $wgSharpenReductionThreshold, $wgSharpenParameter, $wgMaxAnimatedGifArea;
385 $im->readImage( $params['srcPath'] );
387 if ( $params['mimeType'] == 'image/jpeg' ) {
388 // Sharpening, see bug 6193
389 if ( ( $params['physicalWidth'] +
$params['physicalHeight'] )
390 / ( $params['srcWidth'] +
$params['srcHeight'] )
391 < $wgSharpenReductionThreshold ) {
392 // Hack, since $wgSharpenParamater is written specifically for the command line convert
393 list( $radius, $sigma ) = explode( 'x', $wgSharpenParameter );
394 $im->sharpenImage( $radius, $sigma );
396 $im->setCompressionQuality( 80 );
397 } elseif ( $params['mimeType'] == 'image/png' ) {
398 $im->setCompressionQuality( 95 );
399 } elseif ( $params['mimeType'] == 'image/gif' ) {
400 if ( $this->getImageArea( $image ) > $wgMaxAnimatedGifArea ) {
401 // Extract initial frame only; we're so big it'll
402 // be a total drag. :P
403 $im->setImageScene( 0 );
404 } elseif ( $this->isAnimatedImage( $image ) ) {
405 // Coalesce is needed to scale animated GIFs properly (bug 1017).
406 $im = $im->coalesceImages();
410 $rotation = $this->getRotation( $image );
411 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
413 $im->setImageBackgroundColor( new ImagickPixel( 'white' ) );
415 // Call Imagick::thumbnailImage on each frame
416 foreach ( $im as $i => $frame ) {
417 if ( !$frame->thumbnailImage( $width, $height, /* fit */ false ) ) {
418 return $this->getMediaTransformError( $params, "Error scaling frame $i" );
421 $im->setImageDepth( 8 );
424 if ( !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) {
425 return $this->getMediaTransformError( $params, "Error rotating $rotation degrees" );
429 if ( $this->isAnimatedImage( $image ) ) {
430 wfDebug( __METHOD__
. ": Writing animated thumbnail\n" );
431 // This is broken somehow... can't find out how to fix it
432 $result = $im->writeImages( $params['dstPath'], true );
434 $result = $im->writeImage( $params['dstPath'] );
437 return $this->getMediaTransformError( $params,
438 "Unable to write thumbnail to {$params['dstPath']}" );
441 } catch ( ImagickException
$e ) {
442 return $this->getMediaTransformError( $params, $e->getMessage() );
450 * Transform an image using a custom command
452 * @param $image File File associated with this thumbnail
453 * @param array $params Array with scaler params
455 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
457 protected function transformCustom( $image, $params ) {
458 # Use a custom convert command
459 global $wgCustomConvertCommand;
461 # Variables: %s %d %w %h
462 $src = wfEscapeShellArg( $params['srcPath'] );
463 $dst = wfEscapeShellArg( $params['dstPath'] );
464 $cmd = $wgCustomConvertCommand;
465 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
466 $cmd = str_replace( '%h', $params['physicalHeight'],
467 str_replace( '%w', $params['physicalWidth'], $cmd ) ); # Size
468 wfDebug( __METHOD__
. ": Running custom convert command $cmd\n" );
469 wfProfileIn( 'convert' );
471 $err = wfShellExecWithStderr( $cmd, $retval );
472 wfProfileOut( 'convert' );
474 if ( $retval !== 0 ) {
475 $this->logErrorForExternalProcess( $retval, $err, $cmd );
476 return $this->getMediaTransformError( $params, $err );
478 return false; # No error
482 * Log an error that occurred in an external process
488 protected function logErrorForExternalProcess( $retval, $err, $cmd ) {
489 wfDebugLog( 'thumbnail',
490 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
491 wfHostname(), $retval, trim( $err ), $cmd ) );
494 * Get a MediaTransformError with error 'thumbnail_error'
496 * @param array $params Parameter array as passed to the transform* functions
497 * @param string $errMsg Error message
498 * @return MediaTransformError
500 public function getMediaTransformError( $params, $errMsg ) {
501 return new MediaTransformError( 'thumbnail_error', $params['clientWidth'],
502 $params['clientHeight'], $errMsg );
506 * Transform an image using the built in GD library
508 * @param $image File File associated with this thumbnail
509 * @param array $params Array with scaler params
511 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
513 protected function transformGd( $image, $params ) {
514 # Use PHP's builtin GD library functions.
516 # First find out what kind of file this is, and select the correct
517 # input routine for this.
520 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
521 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( __CLASS__
, 'imageJpegWrapper' ) ),
522 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
523 'image/vnd.wap.wbmp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
524 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
526 if ( !isset( $typemap[$params['mimeType']] ) ) {
527 $err = 'Image type not supported';
529 $errMsg = wfMessage( 'thumbnail_image-type' )->text();
530 return $this->getMediaTransformError( $params, $errMsg );
532 list( $loader, $colorStyle, $saveType ) = $typemap[$params['mimeType']];
534 if ( !function_exists( $loader ) ) {
535 $err = "Incomplete GD library configuration: missing function $loader";
537 $errMsg = wfMessage( 'thumbnail_gd-library', $loader )->text();
538 return $this->getMediaTransformError( $params, $errMsg );
541 if ( !file_exists( $params['srcPath'] ) ) {
542 $err = "File seems to be missing: {$params['srcPath']}";
544 $errMsg = wfMessage( 'thumbnail_image-missing', $params['srcPath'] )->text();
545 return $this->getMediaTransformError( $params, $errMsg );
548 $src_image = call_user_func( $loader, $params['srcPath'] );
550 $rotation = function_exists( 'imagerotate' ) ?
$this->getRotation( $image ) : 0;
551 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
552 $dst_image = imagecreatetruecolor( $width, $height );
554 // Initialise the destination image to transparent instead of
555 // the default solid black, to support PNG and GIF transparency nicely
556 $background = imagecolorallocate( $dst_image, 0, 0, 0 );
557 imagecolortransparent( $dst_image, $background );
558 imagealphablending( $dst_image, false );
560 if ( $colorStyle == 'palette' ) {
561 // Don't resample for paletted GIF images.
562 // It may just uglify them, and completely breaks transparency.
563 imagecopyresized( $dst_image, $src_image,
566 imagesx( $src_image ), imagesy( $src_image ) );
568 imagecopyresampled( $dst_image, $src_image,
571 imagesx( $src_image ), imagesy( $src_image ) );
574 if ( $rotation %
360 != 0 && $rotation %
90 == 0 ) {
575 $rot_image = imagerotate( $dst_image, $rotation, 0 );
576 imagedestroy( $dst_image );
577 $dst_image = $rot_image;
580 imagesavealpha( $dst_image, true );
582 call_user_func( $saveType, $dst_image, $params['dstPath'] );
583 imagedestroy( $dst_image );
584 imagedestroy( $src_image );
586 return false; # No error
590 * Escape a string for ImageMagick's property input (e.g. -set -comment)
591 * See InterpretImageProperties() in magick/property.c
592 * @return mixed|string
594 function escapeMagickProperty( $s ) {
595 // Double the backslashes
596 $s = str_replace( '\\', '\\\\', $s );
597 // Double the percents
598 $s = str_replace( '%', '%%', $s );
599 // Escape initial - or @
600 if ( strlen( $s ) > 0 && ( $s[0] === '-' ||
$s[0] === '@' ) ) {
607 * Escape a string for ImageMagick's input filenames. See ExpandFilenames()
608 * and GetPathComponent() in magick/utility.c.
610 * This won't work with an initial ~ or @, so input files should be prefixed
611 * with the directory name.
613 * Glob character unescaping is broken in ImageMagick before 6.6.1-5, but
614 * it's broken in a way that doesn't involve trying to convert every file
615 * in a directory, so we're better off escaping and waiting for the bugfix
616 * to filter down to users.
618 * @param string $path The file path
619 * @param bool|string $scene The scene specification, or false if there is none
620 * @throws MWException
623 function escapeMagickInput( $path, $scene = false ) {
624 # Die on initial metacharacters (caller should prepend path)
625 $firstChar = substr( $path, 0, 1 );
626 if ( $firstChar === '~' ||
$firstChar === '@' ) {
627 throw new MWException( __METHOD__
. ': cannot escape this path name' );
631 $path = preg_replace( '/[*?\[\]{}]/', '\\\\\0', $path );
633 return $this->escapeMagickPath( $path, $scene );
637 * Escape a string for ImageMagick's output filename. See
638 * InterpretImageFilename() in magick/image.c.
641 function escapeMagickOutput( $path, $scene = false ) {
642 $path = str_replace( '%', '%%', $path );
643 return $this->escapeMagickPath( $path, $scene );
647 * Armour a string against ImageMagick's GetPathComponent(). This is a
648 * helper function for escapeMagickInput() and escapeMagickOutput().
650 * @param string $path The file path
651 * @param bool|string $scene The scene specification, or false if there is none
652 * @throws MWException
655 protected function escapeMagickPath( $path, $scene = false ) {
656 # Die on format specifiers (other than drive letters). The regex is
657 # meant to match all the formats you get from "convert -list format"
658 if ( preg_match( '/^([a-zA-Z0-9-]+):/', $path, $m ) ) {
659 if ( wfIsWindows() && is_dir( $m[0] ) ) {
660 // OK, it's a drive letter
661 // ImageMagick has a similar exception, see IsMagickConflict()
663 throw new MWException( __METHOD__
. ': unexpected colon character in path name' );
667 # If there are square brackets, add a do-nothing scene specification
668 # to force a literal interpretation
669 if ( $scene === false ) {
670 if ( strpos( $path, '[' ) !== false ) {
680 * Retrieve the version of the installed ImageMagick
681 * You can use PHPs version_compare() to use this value
682 * Value is cached for one hour.
683 * @return String representing the IM version.
685 protected function getMagickVersion() {
688 $cache = $wgMemc->get( "imagemagick-version" );
690 global $wgImageMagickConvertCommand;
691 $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . ' -version';
692 wfDebug( __METHOD__
. ": Running convert -version\n" );
694 $return = wfShellExec( $cmd, $retval );
695 $x = preg_match( '/Version: ImageMagick ([0-9]*\.[0-9]*\.[0-9]*)/', $return, $matches );
697 wfDebug( __METHOD__
. ": ImageMagick version check failed\n" );
700 $wgMemc->set( "imagemagick-version", $matches[1], 3600 );
706 static function imageJpegWrapper( $dst_image, $thumbPath ) {
707 imageinterlace( $dst_image );
708 imagejpeg( $dst_image, $thumbPath, 95 );
712 * Returns whether the current scaler supports rotation (im and gd do)
716 public static function canRotate() {
717 $scaler = self
::getScalerType( null, false );
720 # ImageMagick supports autorotation
723 # Imagick::rotateImage
726 # GD's imagerotate function is used to rotate images, but not
727 # all precompiled PHP versions have that function
728 return function_exists( 'imagerotate' );
730 # Other scalers don't support rotation
737 * @param array $params Rotate parameters.
738 * 'rotation' clockwise rotation in degrees, allowed are multiples of 90
742 public function rotate( $file, $params ) {
743 global $wgImageMagickConvertCommand;
745 $rotation = ( $params['rotation'] +
$this->getRotation( $file ) ) %
360;
748 $scaler = self
::getScalerType( null, false );
751 $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . " " .
752 wfEscapeShellArg( $this->escapeMagickInput( $params['srcPath'], $scene ) ) .
753 " -rotate -$rotation " .
754 wfEscapeShellArg( $this->escapeMagickOutput( $params['dstPath'] ) );
755 wfDebug( __METHOD__
. ": running ImageMagick: $cmd\n" );
756 wfProfileIn( 'convert' );
758 $err = wfShellExecWithStderr( $cmd, $retval, $env );
759 wfProfileOut( 'convert' );
760 if ( $retval !== 0 ) {
761 $this->logErrorForExternalProcess( $retval, $err, $cmd );
762 return new MediaTransformError( 'thumbnail_error', 0, 0, $err );
767 $im->readImage( $params['srcPath'] );
768 if ( !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) {
769 return new MediaTransformError( 'thumbnail_error', 0, 0,
770 "Error rotating $rotation degrees" );
772 $result = $im->writeImage( $params['dstPath'] );
774 return new MediaTransformError( 'thumbnail_error', 0, 0,
775 "Unable to write image to {$params['dstPath']}" );
779 return new MediaTransformError( 'thumbnail_error', 0, 0,
780 "$scaler rotation not implemented" );
785 * Rerurns whether the file needs to be rendered. Returns true if the
786 * file requires rotation and we are able to rotate it.
791 public function mustRender( $file ) {
792 return self
::canRotate() && $this->getRotation( $file ) != 0;