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 );
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'] );
195 wfRunHooks( 'BitmapHandlerTransform', array( $this, $image, &$scalerParams, &$mto ) );
196 if ( !is_null( $mto ) ) {
197 wfDebug( __METHOD__
. ": Hook to BitmapHandlerTransform created an mto\n" );
198 $scaler = 'hookaborted';
203 # Handled by the hook above
204 $err = $mto->isError() ?
$mto : false;
207 $err = $this->transformImageMagick( $image, $scalerParams );
210 $err = $this->transformCustom( $image, $scalerParams );
213 $err = $this->transformImageMagickExt( $image, $scalerParams );
217 $err = $this->transformGd( $image, $scalerParams );
221 # Remove the file if a zero-byte thumbnail was created, or if there was an error
222 $removed = $this->removeBadFile( $dstPath, (bool)$err );
224 # transform returned MediaTransforError
226 } elseif ( $removed ) {
227 # Thumbnail was zero-byte and had to be removed
228 return new MediaTransformError( 'thumbnail_error',
229 $scalerParams['clientWidth'], $scalerParams['clientHeight'] );
234 'width' => $scalerParams['clientWidth'],
235 'height' => $scalerParams['clientHeight']
238 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
243 * Returns which scaler type should be used. Creates parent directories
244 * for $dstPath and returns 'client' on error
246 * @return string client,im,custom,gd
248 protected static function getScalerType( $dstPath, $checkDstPath = true ) {
249 global $wgUseImageResize, $wgUseImageMagick, $wgCustomConvertCommand;
251 if ( !$dstPath && $checkDstPath ) {
252 # No output path available, client side scaling only
254 } elseif ( !$wgUseImageResize ) {
256 } elseif ( $wgUseImageMagick ) {
258 } elseif ( $wgCustomConvertCommand ) {
260 } elseif ( function_exists( 'imagecreatetruecolor' ) ) {
262 } elseif ( class_exists( 'Imagick' ) ) {
272 * Get a ThumbnailImage that respresents an image that will be scaled
275 * @param $image File File associated with this thumbnail
276 * @param array $scalerParams Array with scaler params
277 * @return ThumbnailImage
279 * @todo fixme: no rotation support
281 protected function getClientScalingThumbnailImage( $image, $scalerParams ) {
283 'width' => $scalerParams['clientWidth'],
284 'height' => $scalerParams['clientHeight']
287 return new ThumbnailImage( $image, $image->getURL(), null, $params );
291 * Transform an image using ImageMagick
293 * @param $image File File associated with this thumbnail
294 * @param array $params Array with scaler params
296 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
298 protected function transformImageMagick( $image, $params ) {
300 global $wgSharpenReductionThreshold, $wgSharpenParameter, $wgMaxAnimatedGifArea,
301 $wgImageMagickTempDir, $wgImageMagickConvertCommand;
307 $animation_post = '';
309 if ( $params['mimeType'] == 'image/jpeg' ) {
310 $quality = "-quality 80"; // 80%
311 # Sharpening, see bug 6193
312 if ( ( $params['physicalWidth'] +
$params['physicalHeight'] )
313 / ( $params['srcWidth'] +
$params['srcHeight'] )
314 < $wgSharpenReductionThreshold
316 $sharpen = "-sharpen " . wfEscapeShellArg( $wgSharpenParameter );
318 if ( version_compare( $this->getMagickVersion(), "6.5.6" ) >= 0 ) {
319 // JPEG decoder hint to reduce memory, available since IM 6.5.6-2
320 $decoderHint = "-define jpeg:size={$params['physicalDimensions']}";
322 } elseif ( $params['mimeType'] == 'image/png' ) {
323 $quality = "-quality 95"; // zlib 9, adaptive filtering
325 } elseif ( $params['mimeType'] == 'image/gif' ) {
326 if ( $this->getImageArea( $image ) > $wgMaxAnimatedGifArea ) {
327 // Extract initial frame only; we're so big it'll
328 // be a total drag. :P
330 } elseif ( $this->isAnimatedImage( $image ) ) {
331 // Coalesce is needed to scale animated GIFs properly (bug 1017).
332 $animation_pre = '-coalesce';
333 // We optimize the output, but -optimize is broken,
334 // use optimizeTransparency instead (bug 11822)
335 if ( version_compare( $this->getMagickVersion(), "6.3.5" ) >= 0 ) {
336 $animation_post = '-fuzz 5% -layers optimizeTransparency';
339 } elseif ( $params['mimeType'] == 'image/x-xcf' ) {
340 $animation_post = '-layers merge';
343 // Use one thread only, to avoid deadlock bugs on OOM
344 $env = array( 'OMP_NUM_THREADS' => 1 );
345 if ( strval( $wgImageMagickTempDir ) !== '' ) {
346 $env['MAGICK_TMPDIR'] = $wgImageMagickTempDir;
349 $rotation = $this->getRotation( $image );
350 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
353 wfEscapeShellArg( $wgImageMagickConvertCommand ) .
354 // Specify white background color, will be used for transparent images
355 // in Internet Explorer/Windows instead of default black.
356 " {$quality} -background white" .
358 wfEscapeShellArg( $this->escapeMagickInput( $params['srcPath'], $scene ) ) .
359 " {$animation_pre}" .
360 // For the -thumbnail option a "!" is needed to force exact size,
361 // or ImageMagick may decide your ratio is wrong and slice off
363 " -thumbnail " . wfEscapeShellArg( "{$width}x{$height}!" ) .
364 // Add the source url as a comment to the thumb, but don't add the flag if there's no comment
365 ( $params['comment'] !== ''
366 ?
" -set comment " . wfEscapeShellArg( $this->escapeMagickProperty( $params['comment'] ) )
368 " -depth 8 $sharpen " .
369 " -rotate -$rotation " .
370 " {$animation_post} " .
371 wfEscapeShellArg( $this->escapeMagickOutput( $params['dstPath'] ) );
373 wfDebug( __METHOD__
. ": running ImageMagick: $cmd\n" );
374 wfProfileIn( 'convert' );
376 $err = wfShellExecWithStderr( $cmd, $retval, $env );
377 wfProfileOut( 'convert' );
379 if ( $retval !== 0 ) {
380 $this->logErrorForExternalProcess( $retval, $err, $cmd );
382 return $this->getMediaTransformError( $params, $err );
385 return false; # No error
389 * Transform an image using the Imagick PHP extension
391 * @param $image File File associated with this thumbnail
392 * @param array $params Array with scaler params
394 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
396 protected function transformImageMagickExt( $image, $params ) {
397 global $wgSharpenReductionThreshold, $wgSharpenParameter, $wgMaxAnimatedGifArea;
401 $im->readImage( $params['srcPath'] );
403 if ( $params['mimeType'] == 'image/jpeg' ) {
404 // Sharpening, see bug 6193
405 if ( ( $params['physicalWidth'] +
$params['physicalHeight'] )
406 / ( $params['srcWidth'] +
$params['srcHeight'] )
407 < $wgSharpenReductionThreshold
409 // Hack, since $wgSharpenParamater is written specifically for the command line convert
410 list( $radius, $sigma ) = explode( 'x', $wgSharpenParameter );
411 $im->sharpenImage( $radius, $sigma );
413 $im->setCompressionQuality( 80 );
414 } elseif ( $params['mimeType'] == 'image/png' ) {
415 $im->setCompressionQuality( 95 );
416 } elseif ( $params['mimeType'] == 'image/gif' ) {
417 if ( $this->getImageArea( $image ) > $wgMaxAnimatedGifArea ) {
418 // Extract initial frame only; we're so big it'll
419 // be a total drag. :P
420 $im->setImageScene( 0 );
421 } elseif ( $this->isAnimatedImage( $image ) ) {
422 // Coalesce is needed to scale animated GIFs properly (bug 1017).
423 $im = $im->coalesceImages();
427 $rotation = $this->getRotation( $image );
428 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
430 $im->setImageBackgroundColor( new ImagickPixel( 'white' ) );
432 // Call Imagick::thumbnailImage on each frame
433 foreach ( $im as $i => $frame ) {
434 if ( !$frame->thumbnailImage( $width, $height, /* fit */ false ) ) {
435 return $this->getMediaTransformError( $params, "Error scaling frame $i" );
438 $im->setImageDepth( 8 );
441 if ( !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) {
442 return $this->getMediaTransformError( $params, "Error rotating $rotation degrees" );
446 if ( $this->isAnimatedImage( $image ) ) {
447 wfDebug( __METHOD__
. ": Writing animated thumbnail\n" );
448 // This is broken somehow... can't find out how to fix it
449 $result = $im->writeImages( $params['dstPath'], true );
451 $result = $im->writeImage( $params['dstPath'] );
454 return $this->getMediaTransformError( $params,
455 "Unable to write thumbnail to {$params['dstPath']}" );
457 } catch ( ImagickException
$e ) {
458 return $this->getMediaTransformError( $params, $e->getMessage() );
465 * Transform an image using a custom command
467 * @param $image File File associated with this thumbnail
468 * @param array $params Array with scaler params
470 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
472 protected function transformCustom( $image, $params ) {
473 # Use a custom convert command
474 global $wgCustomConvertCommand;
476 # Variables: %s %d %w %h
477 $src = wfEscapeShellArg( $params['srcPath'] );
478 $dst = wfEscapeShellArg( $params['dstPath'] );
479 $cmd = $wgCustomConvertCommand;
480 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
481 $cmd = str_replace( '%h', $params['physicalHeight'],
482 str_replace( '%w', $params['physicalWidth'], $cmd ) ); # Size
483 wfDebug( __METHOD__
. ": Running custom convert command $cmd\n" );
484 wfProfileIn( 'convert' );
486 $err = wfShellExecWithStderr( $cmd, $retval );
487 wfProfileOut( 'convert' );
489 if ( $retval !== 0 ) {
490 $this->logErrorForExternalProcess( $retval, $err, $cmd );
492 return $this->getMediaTransformError( $params, $err );
495 return false; # No error
499 * Log an error that occurred in an external process
505 protected function logErrorForExternalProcess( $retval, $err, $cmd ) {
506 wfDebugLog( 'thumbnail',
507 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
508 wfHostname(), $retval, trim( $err ), $cmd ) );
512 * Get a MediaTransformError with error 'thumbnail_error'
514 * @param array $params Parameter array as passed to the transform* functions
515 * @param string $errMsg Error message
516 * @return MediaTransformError
518 public function getMediaTransformError( $params, $errMsg ) {
519 return new MediaTransformError( 'thumbnail_error', $params['clientWidth'],
520 $params['clientHeight'], $errMsg );
524 * Transform an image using the built in GD library
526 * @param $image File File associated with this thumbnail
527 * @param array $params Array with scaler params
529 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
531 protected function transformGd( $image, $params ) {
532 # Use PHP's builtin GD library functions.
534 # First find out what kind of file this is, and select the correct
535 # input routine for this.
538 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
539 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor',
540 array( __CLASS__
, 'imageJpegWrapper' ) ),
541 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
542 'image/vnd.wap.wbmp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
543 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
545 if ( !isset( $typemap[$params['mimeType']] ) ) {
546 $err = 'Image type not supported';
548 $errMsg = wfMessage( 'thumbnail_image-type' )->text();
550 return $this->getMediaTransformError( $params, $errMsg );
552 list( $loader, $colorStyle, $saveType ) = $typemap[$params['mimeType']];
554 if ( !function_exists( $loader ) ) {
555 $err = "Incomplete GD library configuration: missing function $loader";
557 $errMsg = wfMessage( 'thumbnail_gd-library', $loader )->text();
559 return $this->getMediaTransformError( $params, $errMsg );
562 if ( !file_exists( $params['srcPath'] ) ) {
563 $err = "File seems to be missing: {$params['srcPath']}";
565 $errMsg = wfMessage( 'thumbnail_image-missing', $params['srcPath'] )->text();
567 return $this->getMediaTransformError( $params, $errMsg );
570 $src_image = call_user_func( $loader, $params['srcPath'] );
572 $rotation = function_exists( 'imagerotate' ) ?
$this->getRotation( $image ) : 0;
573 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
574 $dst_image = imagecreatetruecolor( $width, $height );
576 // Initialise the destination image to transparent instead of
577 // the default solid black, to support PNG and GIF transparency nicely
578 $background = imagecolorallocate( $dst_image, 0, 0, 0 );
579 imagecolortransparent( $dst_image, $background );
580 imagealphablending( $dst_image, false );
582 if ( $colorStyle == 'palette' ) {
583 // Don't resample for paletted GIF images.
584 // It may just uglify them, and completely breaks transparency.
585 imagecopyresized( $dst_image, $src_image,
588 imagesx( $src_image ), imagesy( $src_image ) );
590 imagecopyresampled( $dst_image, $src_image,
593 imagesx( $src_image ), imagesy( $src_image ) );
596 if ( $rotation %
360 != 0 && $rotation %
90 == 0 ) {
597 $rot_image = imagerotate( $dst_image, $rotation, 0 );
598 imagedestroy( $dst_image );
599 $dst_image = $rot_image;
602 imagesavealpha( $dst_image, true );
604 call_user_func( $saveType, $dst_image, $params['dstPath'] );
605 imagedestroy( $dst_image );
606 imagedestroy( $src_image );
608 return false; # No error
612 * Escape a string for ImageMagick's property input (e.g. -set -comment)
613 * See InterpretImageProperties() in magick/property.c
614 * @return mixed|string
616 function escapeMagickProperty( $s ) {
617 // Double the backslashes
618 $s = str_replace( '\\', '\\\\', $s );
619 // Double the percents
620 $s = str_replace( '%', '%%', $s );
621 // Escape initial - or @
622 if ( strlen( $s ) > 0 && ( $s[0] === '-' ||
$s[0] === '@' ) ) {
630 * Escape a string for ImageMagick's input filenames. See ExpandFilenames()
631 * and GetPathComponent() in magick/utility.c.
633 * This won't work with an initial ~ or @, so input files should be prefixed
634 * with the directory name.
636 * Glob character unescaping is broken in ImageMagick before 6.6.1-5, but
637 * it's broken in a way that doesn't involve trying to convert every file
638 * in a directory, so we're better off escaping and waiting for the bugfix
639 * to filter down to users.
641 * @param string $path The file path
642 * @param bool|string $scene The scene specification, or false if there is none
643 * @throws MWException
646 function escapeMagickInput( $path, $scene = false ) {
647 # Die on initial metacharacters (caller should prepend path)
648 $firstChar = substr( $path, 0, 1 );
649 if ( $firstChar === '~' ||
$firstChar === '@' ) {
650 throw new MWException( __METHOD__
. ': cannot escape this path name' );
654 $path = preg_replace( '/[*?\[\]{}]/', '\\\\\0', $path );
656 return $this->escapeMagickPath( $path, $scene );
660 * Escape a string for ImageMagick's output filename. See
661 * InterpretImageFilename() in magick/image.c.
664 function escapeMagickOutput( $path, $scene = false ) {
665 $path = str_replace( '%', '%%', $path );
667 return $this->escapeMagickPath( $path, $scene );
671 * Armour a string against ImageMagick's GetPathComponent(). This is a
672 * helper function for escapeMagickInput() and escapeMagickOutput().
674 * @param string $path The file path
675 * @param bool|string $scene The scene specification, or false if there is none
676 * @throws MWException
679 protected function escapeMagickPath( $path, $scene = false ) {
680 # Die on format specifiers (other than drive letters). The regex is
681 # meant to match all the formats you get from "convert -list format"
682 if ( preg_match( '/^([a-zA-Z0-9-]+):/', $path, $m ) ) {
683 if ( wfIsWindows() && is_dir( $m[0] ) ) {
684 // OK, it's a drive letter
685 // ImageMagick has a similar exception, see IsMagickConflict()
687 throw new MWException( __METHOD__
. ': unexpected colon character in path name' );
691 # If there are square brackets, add a do-nothing scene specification
692 # to force a literal interpretation
693 if ( $scene === false ) {
694 if ( strpos( $path, '[' ) !== false ) {
705 * Retrieve the version of the installed ImageMagick
706 * You can use PHPs version_compare() to use this value
707 * Value is cached for one hour.
708 * @return String representing the IM version.
710 protected function getMagickVersion() {
713 $cache = $wgMemc->get( "imagemagick-version" );
715 global $wgImageMagickConvertCommand;
716 $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . ' -version';
717 wfDebug( __METHOD__
. ": Running convert -version\n" );
719 $return = wfShellExec( $cmd, $retval );
720 $x = preg_match( '/Version: ImageMagick ([0-9]*\.[0-9]*\.[0-9]*)/', $return, $matches );
722 wfDebug( __METHOD__
. ": ImageMagick version check failed\n" );
726 $wgMemc->set( "imagemagick-version", $matches[1], 3600 );
734 static function imageJpegWrapper( $dst_image, $thumbPath ) {
735 imageinterlace( $dst_image );
736 imagejpeg( $dst_image, $thumbPath, 95 );
740 * Returns whether the current scaler supports rotation (im and gd do)
744 public static function canRotate() {
745 $scaler = self
::getScalerType( null, false );
748 # ImageMagick supports autorotation
751 # Imagick::rotateImage
754 # GD's imagerotate function is used to rotate images, but not
755 # all precompiled PHP versions have that function
756 return function_exists( 'imagerotate' );
758 # Other scalers don't support rotation
765 * @param array $params Rotate parameters.
766 * 'rotation' clockwise rotation in degrees, allowed are multiples of 90
770 public function rotate( $file, $params ) {
771 global $wgImageMagickConvertCommand;
773 $rotation = ( $params['rotation'] +
$this->getRotation( $file ) ) %
360;
776 $scaler = self
::getScalerType( null, false );
779 $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . " " .
780 wfEscapeShellArg( $this->escapeMagickInput( $params['srcPath'], $scene ) ) .
781 " -rotate -$rotation " .
782 wfEscapeShellArg( $this->escapeMagickOutput( $params['dstPath'] ) );
783 wfDebug( __METHOD__
. ": running ImageMagick: $cmd\n" );
784 wfProfileIn( 'convert' );
786 $err = wfShellExecWithStderr( $cmd, $retval, $env );
787 wfProfileOut( 'convert' );
788 if ( $retval !== 0 ) {
789 $this->logErrorForExternalProcess( $retval, $err, $cmd );
791 return new MediaTransformError( 'thumbnail_error', 0, 0, $err );
797 $im->readImage( $params['srcPath'] );
798 if ( !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) {
799 return new MediaTransformError( 'thumbnail_error', 0, 0,
800 "Error rotating $rotation degrees" );
802 $result = $im->writeImage( $params['dstPath'] );
804 return new MediaTransformError( 'thumbnail_error', 0, 0,
805 "Unable to write image to {$params['dstPath']}" );
810 return new MediaTransformError( 'thumbnail_error', 0, 0,
811 "$scaler rotation not implemented" );
816 * Rerurns whether the file needs to be rendered. Returns true if the
817 * file requires rotation and we are able to rotate it.
822 public function mustRender( $file ) {
823 return self
::canRotate() && $this->getRotation( $file ) != 0;