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 if ( isset( $params['quality'] ) && $params['quality'] === 'low' ) {
142 $scalerParams['quality'] = 30;
145 # Determine scaler type
146 $scaler = self
::getScalerType( $dstPath );
148 wfDebug( __METHOD__
. ": creating {$scalerParams['physicalDimensions']} " .
149 "thumbnail at $dstPath using scaler $scaler\n" );
151 if ( !$image->mustRender() &&
152 $scalerParams['physicalWidth'] == $scalerParams['srcWidth']
153 && $scalerParams['physicalHeight'] == $scalerParams['srcHeight']
154 && !isset( $scalerParams['quality'] )
157 # normaliseParams (or the user) wants us to return the unscaled image
158 wfDebug( __METHOD__
. ": returning unscaled image\n" );
160 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
163 if ( $scaler == 'client' ) {
164 # Client-side image scaling, use the source URL
165 # Using the destination URL in a TRANSFORM_LATER request would be incorrect
166 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
169 if ( $flags & self
::TRANSFORM_LATER
) {
170 wfDebug( __METHOD__
. ": Transforming later per flags.\n" );
172 'width' => $scalerParams['clientWidth'],
173 'height' => $scalerParams['clientHeight']
175 if ( isset( $params['quality'] ) ) {
176 $newParams['quality'] = $params['quality'];
178 return new ThumbnailImage( $image, $dstUrl, false, $newParams );
181 # Try to make a target path for the thumbnail
182 if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__
) ) {
183 wfDebug( __METHOD__
. ": Unable to create thumbnail destination " .
184 "directory, falling back to client scaling\n" );
186 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
189 # Transform functions and binaries need a FS source file
190 $scalerParams['srcPath'] = $image->getLocalRefPath();
191 if ( $scalerParams['srcPath'] === false ) { // Failed to get local copy
192 wfDebugLog( 'thumbnail',
193 sprintf( 'Thumbnail failed on %s: could not get local copy of "%s"',
194 wfHostname(), $image->getName() ) );
196 return new MediaTransformError( 'thumbnail_error',
197 $scalerParams['clientWidth'], $scalerParams['clientHeight'],
198 wfMessage( 'filemissing' )->text()
204 wfRunHooks( 'BitmapHandlerTransform', array( $this, $image, &$scalerParams, &$mto ) );
205 if ( !is_null( $mto ) ) {
206 wfDebug( __METHOD__
. ": Hook to BitmapHandlerTransform created an mto\n" );
207 $scaler = 'hookaborted';
212 # Handled by the hook above
213 /** @var MediaTransformOutput $mto */
214 $err = $mto->isError() ?
$mto : false;
217 $err = $this->transformImageMagick( $image, $scalerParams );
220 $err = $this->transformCustom( $image, $scalerParams );
223 $err = $this->transformImageMagickExt( $image, $scalerParams );
227 $err = $this->transformGd( $image, $scalerParams );
231 # Remove the file if a zero-byte thumbnail was created, or if there was an error
232 $removed = $this->removeBadFile( $dstPath, (bool)$err );
234 # transform returned MediaTransforError
236 } elseif ( $removed ) {
237 # Thumbnail was zero-byte and had to be removed
238 return new MediaTransformError( 'thumbnail_error',
239 $scalerParams['clientWidth'], $scalerParams['clientHeight'],
240 wfMessage( 'unknown-error' )->text()
246 'width' => $scalerParams['clientWidth'],
247 'height' => $scalerParams['clientHeight']
249 if ( isset( $params['quality'] ) ) {
250 $newParams['quality'] = $params['quality'];
252 return new ThumbnailImage( $image, $dstUrl, $dstPath, $newParams );
257 * Returns which scaler type should be used. Creates parent directories
258 * for $dstPath and returns 'client' on error
260 * @param string $dstPath
261 * @param bool $checkDstPath
262 * @return string One of client, im, custom, gd, imext
264 protected static function getScalerType( $dstPath, $checkDstPath = true ) {
265 global $wgUseImageResize, $wgUseImageMagick, $wgCustomConvertCommand;
267 if ( !$dstPath && $checkDstPath ) {
268 # No output path available, client side scaling only
270 } elseif ( !$wgUseImageResize ) {
272 } elseif ( $wgUseImageMagick ) {
274 } elseif ( $wgCustomConvertCommand ) {
276 } elseif ( function_exists( 'imagecreatetruecolor' ) ) {
278 } elseif ( class_exists( 'Imagick' ) ) {
288 * Get a ThumbnailImage that respresents an image that will be scaled
291 * @param File $image File associated with this thumbnail
292 * @param array $scalerParams Array with scaler params
293 * @return ThumbnailImage
295 * @todo FIXME: No rotation support
297 protected function getClientScalingThumbnailImage( $image, $scalerParams ) {
299 'width' => $scalerParams['clientWidth'],
300 'height' => $scalerParams['clientHeight']
303 return new ThumbnailImage( $image, $image->getURL(), null, $params );
307 * Transform an image using ImageMagick
309 * @param File $image File associated with this thumbnail
310 * @param array $params Array with scaler params
312 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
314 protected function transformImageMagick( $image, $params ) {
316 global $wgSharpenReductionThreshold, $wgSharpenParameter, $wgMaxAnimatedGifArea,
317 $wgImageMagickTempDir, $wgImageMagickConvertCommand;
322 $animation_pre = array();
323 $animation_post = array();
324 $decoderHint = array();
325 if ( $params['mimeType'] == 'image/jpeg' ) {
326 $qualityVal = isset( $params['quality'] ) ?
(string) $params['quality'] : null;
327 $quality = array( '-quality', $qualityVal ?
: '80' ); // 80%
328 # Sharpening, see bug 6193
329 if ( ( $params['physicalWidth'] +
$params['physicalHeight'] )
330 / ( $params['srcWidth'] +
$params['srcHeight'] )
331 < $wgSharpenReductionThreshold
333 $sharpen = array( '-sharpen', $wgSharpenParameter );
335 if ( version_compare( $this->getMagickVersion(), "6.5.6" ) >= 0 ) {
336 // JPEG decoder hint to reduce memory, available since IM 6.5.6-2
337 $decoderHint = array( '-define', "jpeg:size={$params['physicalDimensions']}" );
339 } elseif ( $params['mimeType'] == 'image/png' ) {
340 $quality = array( '-quality', '95' ); // zlib 9, adaptive filtering
342 } elseif ( $params['mimeType'] == 'image/gif' ) {
343 if ( $this->getImageArea( $image ) > $wgMaxAnimatedGifArea ) {
344 // Extract initial frame only; we're so big it'll
345 // be a total drag. :P
347 } elseif ( $this->isAnimatedImage( $image ) ) {
348 // Coalesce is needed to scale animated GIFs properly (bug 1017).
349 $animation_pre = array( '-coalesce' );
350 // We optimize the output, but -optimize is broken,
351 // use optimizeTransparency instead (bug 11822)
352 if ( version_compare( $this->getMagickVersion(), "6.3.5" ) >= 0 ) {
353 $animation_post = array( '-fuzz', '5%', '-layers', 'optimizeTransparency' );
356 } elseif ( $params['mimeType'] == 'image/x-xcf' ) {
357 $animation_post = array( '-layers', 'merge' );
360 // Use one thread only, to avoid deadlock bugs on OOM
361 $env = array( 'OMP_NUM_THREADS' => 1 );
362 if ( strval( $wgImageMagickTempDir ) !== '' ) {
363 $env['MAGICK_TMPDIR'] = $wgImageMagickTempDir;
366 $rotation = $this->getRotation( $image );
367 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
369 $cmd = call_user_func_array( 'wfEscapeShellArg', array_merge(
370 array( $wgImageMagickConvertCommand ),
372 // Specify white background color, will be used for transparent images
373 // in Internet Explorer/Windows instead of default black.
374 array( '-background', 'white' ),
376 array( $this->escapeMagickInput( $params['srcPath'], $scene ) ),
378 // For the -thumbnail option a "!" is needed to force exact size,
379 // or ImageMagick may decide your ratio is wrong and slice off
381 array( '-thumbnail', "{$width}x{$height}!" ),
382 // Add the source url as a comment to the thumb, but don't add the flag if there's no comment
383 ( $params['comment'] !== ''
384 ?
array( '-set', 'comment', $this->escapeMagickProperty( $params['comment'] ) )
386 array( '-depth', 8 ),
388 array( '-rotate', "-$rotation" ),
390 array( $this->escapeMagickOutput( $params['dstPath'] ) ) ) );
392 wfDebug( __METHOD__
. ": running ImageMagick: $cmd\n" );
393 wfProfileIn( 'convert' );
395 $err = wfShellExecWithStderr( $cmd, $retval, $env );
396 wfProfileOut( 'convert' );
398 if ( $retval !== 0 ) {
399 $this->logErrorForExternalProcess( $retval, $err, $cmd );
401 return $this->getMediaTransformError( $params, "$err\nError code: $retval" );
404 return false; # No error
408 * Transform an image using the Imagick PHP extension
410 * @param File $image File associated with this thumbnail
411 * @param array $params Array with scaler params
413 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
415 protected function transformImageMagickExt( $image, $params ) {
416 global $wgSharpenReductionThreshold, $wgSharpenParameter, $wgMaxAnimatedGifArea;
420 $im->readImage( $params['srcPath'] );
422 if ( $params['mimeType'] == 'image/jpeg' ) {
423 // Sharpening, see bug 6193
424 if ( ( $params['physicalWidth'] +
$params['physicalHeight'] )
425 / ( $params['srcWidth'] +
$params['srcHeight'] )
426 < $wgSharpenReductionThreshold
428 // Hack, since $wgSharpenParamater is written specifically for the command line convert
429 list( $radius, $sigma ) = explode( 'x', $wgSharpenParameter );
430 $im->sharpenImage( $radius, $sigma );
432 $qualityVal = isset( $params['quality'] ) ?
(string) $params['quality'] : null;
433 $im->setCompressionQuality( $qualityVal ?
: 80 );
434 } elseif ( $params['mimeType'] == 'image/png' ) {
435 $im->setCompressionQuality( 95 );
436 } elseif ( $params['mimeType'] == 'image/gif' ) {
437 if ( $this->getImageArea( $image ) > $wgMaxAnimatedGifArea ) {
438 // Extract initial frame only; we're so big it'll
439 // be a total drag. :P
440 $im->setImageScene( 0 );
441 } elseif ( $this->isAnimatedImage( $image ) ) {
442 // Coalesce is needed to scale animated GIFs properly (bug 1017).
443 $im = $im->coalesceImages();
447 $rotation = $this->getRotation( $image );
448 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
450 $im->setImageBackgroundColor( new ImagickPixel( 'white' ) );
452 // Call Imagick::thumbnailImage on each frame
453 foreach ( $im as $i => $frame ) {
454 if ( !$frame->thumbnailImage( $width, $height, /* fit */ false ) ) {
455 return $this->getMediaTransformError( $params, "Error scaling frame $i" );
458 $im->setImageDepth( 8 );
461 if ( !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) {
462 return $this->getMediaTransformError( $params, "Error rotating $rotation degrees" );
466 if ( $this->isAnimatedImage( $image ) ) {
467 wfDebug( __METHOD__
. ": Writing animated thumbnail\n" );
468 // This is broken somehow... can't find out how to fix it
469 $result = $im->writeImages( $params['dstPath'], true );
471 $result = $im->writeImage( $params['dstPath'] );
474 return $this->getMediaTransformError( $params,
475 "Unable to write thumbnail to {$params['dstPath']}" );
477 } catch ( ImagickException
$e ) {
478 return $this->getMediaTransformError( $params, $e->getMessage() );
485 * Transform an image using a custom command
487 * @param File $image File associated with this thumbnail
488 * @param array $params Array with scaler params
490 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
492 protected function transformCustom( $image, $params ) {
493 # Use a custom convert command
494 global $wgCustomConvertCommand;
496 # Variables: %s %d %w %h
497 $src = wfEscapeShellArg( $params['srcPath'] );
498 $dst = wfEscapeShellArg( $params['dstPath'] );
499 $cmd = $wgCustomConvertCommand;
500 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
501 $cmd = str_replace( '%h', wfEscapeShellArg( $params['physicalHeight'] ),
502 str_replace( '%w', wfEscapeShellArg( $params['physicalWidth'] ), $cmd ) ); # Size
503 wfDebug( __METHOD__
. ": Running custom convert command $cmd\n" );
504 wfProfileIn( 'convert' );
506 $err = wfShellExecWithStderr( $cmd, $retval );
507 wfProfileOut( 'convert' );
509 if ( $retval !== 0 ) {
510 $this->logErrorForExternalProcess( $retval, $err, $cmd );
512 return $this->getMediaTransformError( $params, $err );
515 return false; # No error
519 * Get a MediaTransformError with error 'thumbnail_error'
521 * @param array $params Parameter array as passed to the transform* functions
522 * @param string $errMsg Error message
523 * @return MediaTransformError
525 public function getMediaTransformError( $params, $errMsg ) {
526 return new MediaTransformError( 'thumbnail_error', $params['clientWidth'],
527 $params['clientHeight'], $errMsg );
531 * Transform an image using the built in GD library
533 * @param File $image File associated with this thumbnail
534 * @param array $params Array with scaler params
536 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
538 protected function transformGd( $image, $params ) {
539 # Use PHP's builtin GD library functions.
541 # First find out what kind of file this is, and select the correct
542 # input routine for this.
545 'image/gif' => array( 'imagecreatefromgif', 'palette', false, 'imagegif' ),
546 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', true,
547 array( __CLASS__
, 'imageJpegWrapper' ) ),
548 'image/png' => array( 'imagecreatefrompng', 'bits', false, 'imagepng' ),
549 'image/vnd.wap.wbmp' => array( 'imagecreatefromwbmp', 'palette', false, 'imagewbmp' ),
550 'image/xbm' => array( 'imagecreatefromxbm', 'palette', false, 'imagexbm' ),
553 if ( !isset( $typemap[$params['mimeType']] ) ) {
554 $err = 'Image type not supported';
556 $errMsg = wfMessage( 'thumbnail_image-type' )->text();
558 return $this->getMediaTransformError( $params, $errMsg );
560 list( $loader, $colorStyle, $useQuality, $saveType ) = $typemap[$params['mimeType']];
562 if ( !function_exists( $loader ) ) {
563 $err = "Incomplete GD library configuration: missing function $loader";
565 $errMsg = wfMessage( 'thumbnail_gd-library', $loader )->text();
567 return $this->getMediaTransformError( $params, $errMsg );
570 if ( !file_exists( $params['srcPath'] ) ) {
571 $err = "File seems to be missing: {$params['srcPath']}";
573 $errMsg = wfMessage( 'thumbnail_image-missing', $params['srcPath'] )->text();
575 return $this->getMediaTransformError( $params, $errMsg );
578 $src_image = call_user_func( $loader, $params['srcPath'] );
580 $rotation = function_exists( 'imagerotate' ) ?
$this->getRotation( $image ) : 0;
581 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
582 $dst_image = imagecreatetruecolor( $width, $height );
584 // Initialise the destination image to transparent instead of
585 // the default solid black, to support PNG and GIF transparency nicely
586 $background = imagecolorallocate( $dst_image, 0, 0, 0 );
587 imagecolortransparent( $dst_image, $background );
588 imagealphablending( $dst_image, false );
590 if ( $colorStyle == 'palette' ) {
591 // Don't resample for paletted GIF images.
592 // It may just uglify them, and completely breaks transparency.
593 imagecopyresized( $dst_image, $src_image,
596 imagesx( $src_image ), imagesy( $src_image ) );
598 imagecopyresampled( $dst_image, $src_image,
601 imagesx( $src_image ), imagesy( $src_image ) );
604 if ( $rotation %
360 != 0 && $rotation %
90 == 0 ) {
605 $rot_image = imagerotate( $dst_image, $rotation, 0 );
606 imagedestroy( $dst_image );
607 $dst_image = $rot_image;
610 imagesavealpha( $dst_image, true );
612 $funcParams = array( $dst_image, $params['dstPath'] );
613 if ( $useQuality && isset( $params['quality'] ) ) {
614 $funcParams[] = $params['quality'];
616 call_user_func_array( $saveType, $funcParams );
618 imagedestroy( $dst_image );
619 imagedestroy( $src_image );
621 return false; # No error
625 * Escape a string for ImageMagick's property input (e.g. -set -comment)
626 * See InterpretImageProperties() in magick/property.c
630 function escapeMagickProperty( $s ) {
631 // Double the backslashes
632 $s = str_replace( '\\', '\\\\', $s );
633 // Double the percents
634 $s = str_replace( '%', '%%', $s );
635 // Escape initial - or @
636 if ( strlen( $s ) > 0 && ( $s[0] === '-' ||
$s[0] === '@' ) ) {
644 * Escape a string for ImageMagick's input filenames. See ExpandFilenames()
645 * and GetPathComponent() in magick/utility.c.
647 * This won't work with an initial ~ or @, so input files should be prefixed
648 * with the directory name.
650 * Glob character unescaping is broken in ImageMagick before 6.6.1-5, but
651 * it's broken in a way that doesn't involve trying to convert every file
652 * in a directory, so we're better off escaping and waiting for the bugfix
653 * to filter down to users.
655 * @param string $path The file path
656 * @param bool|string $scene The scene specification, or false if there is none
657 * @throws MWException
660 function escapeMagickInput( $path, $scene = false ) {
661 # Die on initial metacharacters (caller should prepend path)
662 $firstChar = substr( $path, 0, 1 );
663 if ( $firstChar === '~' ||
$firstChar === '@' ) {
664 throw new MWException( __METHOD__
. ': cannot escape this path name' );
668 $path = preg_replace( '/[*?\[\]{}]/', '\\\\\0', $path );
670 return $this->escapeMagickPath( $path, $scene );
674 * Escape a string for ImageMagick's output filename. See
675 * InterpretImageFilename() in magick/image.c.
676 * @param string $path The file path
677 * @param bool|string $scene The scene specification, or false if there is none
680 function escapeMagickOutput( $path, $scene = false ) {
681 $path = str_replace( '%', '%%', $path );
683 return $this->escapeMagickPath( $path, $scene );
687 * Armour a string against ImageMagick's GetPathComponent(). This is a
688 * helper function for escapeMagickInput() and escapeMagickOutput().
690 * @param string $path The file path
691 * @param bool|string $scene The scene specification, or false if there is none
692 * @throws MWException
695 protected function escapeMagickPath( $path, $scene = false ) {
696 # Die on format specifiers (other than drive letters). The regex is
697 # meant to match all the formats you get from "convert -list format"
698 if ( preg_match( '/^([a-zA-Z0-9-]+):/', $path, $m ) ) {
699 if ( wfIsWindows() && is_dir( $m[0] ) ) {
700 // OK, it's a drive letter
701 // ImageMagick has a similar exception, see IsMagickConflict()
703 throw new MWException( __METHOD__
. ': unexpected colon character in path name' );
707 # If there are square brackets, add a do-nothing scene specification
708 # to force a literal interpretation
709 if ( $scene === false ) {
710 if ( strpos( $path, '[' ) !== false ) {
721 * Retrieve the version of the installed ImageMagick
722 * You can use PHPs version_compare() to use this value
723 * Value is cached for one hour.
724 * @return string Representing the IM version.
726 protected function getMagickVersion() {
729 $cache = $wgMemc->get( "imagemagick-version" );
731 global $wgImageMagickConvertCommand;
732 $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . ' -version';
733 wfDebug( __METHOD__
. ": Running convert -version\n" );
735 $return = wfShellExec( $cmd, $retval );
736 $x = preg_match( '/Version: ImageMagick ([0-9]*\.[0-9]*\.[0-9]*)/', $return, $matches );
738 wfDebug( __METHOD__
. ": ImageMagick version check failed\n" );
742 $wgMemc->set( "imagemagick-version", $matches[1], 3600 );
750 // FIXME: transformImageMagick() & transformImageMagickExt() uses JPEG quality 80, here it's 95?
751 static function imageJpegWrapper( $dst_image, $thumbPath, $quality = 95 ) {
752 imageinterlace( $dst_image );
753 imagejpeg( $dst_image, $thumbPath, $quality );
757 * Returns whether the current scaler supports rotation (im and gd do)
761 public static function canRotate() {
762 $scaler = self
::getScalerType( null, false );
765 # ImageMagick supports autorotation
768 # Imagick::rotateImage
771 # GD's imagerotate function is used to rotate images, but not
772 # all precompiled PHP versions have that function
773 return function_exists( 'imagerotate' );
775 # Other scalers don't support rotation
781 * @see $wgEnableAutoRotation
782 * @return bool Whether auto rotation is enabled
784 public static function autoRotateEnabled() {
785 global $wgEnableAutoRotation;
787 if ( $wgEnableAutoRotation === null ) {
788 // Only enable auto-rotation when the bitmap handler can rotate
789 $wgEnableAutoRotation = BitmapHandler
::canRotate();
792 return $wgEnableAutoRotation;
797 * @param array $params Rotate parameters.
798 * 'rotation' clockwise rotation in degrees, allowed are multiples of 90
802 public function rotate( $file, $params ) {
803 global $wgImageMagickConvertCommand;
805 $rotation = ( $params['rotation'] +
$this->getRotation( $file ) ) %
360;
808 $scaler = self
::getScalerType( null, false );
811 $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . " " .
812 wfEscapeShellArg( $this->escapeMagickInput( $params['srcPath'], $scene ) ) .
813 " -rotate " . wfEscapeShellArg( "-$rotation" ) . " " .
814 wfEscapeShellArg( $this->escapeMagickOutput( $params['dstPath'] ) );
815 wfDebug( __METHOD__
. ": running ImageMagick: $cmd\n" );
816 wfProfileIn( 'convert' );
818 $err = wfShellExecWithStderr( $cmd, $retval );
819 wfProfileOut( 'convert' );
820 if ( $retval !== 0 ) {
821 $this->logErrorForExternalProcess( $retval, $err, $cmd );
823 return new MediaTransformError( 'thumbnail_error', 0, 0, $err );
829 $im->readImage( $params['srcPath'] );
830 if ( !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) {
831 return new MediaTransformError( 'thumbnail_error', 0, 0,
832 "Error rotating $rotation degrees" );
834 $result = $im->writeImage( $params['dstPath'] );
836 return new MediaTransformError( 'thumbnail_error', 0, 0,
837 "Unable to write image to {$params['dstPath']}" );
842 return new MediaTransformError( 'thumbnail_error', 0, 0,
843 "$scaler rotation not implemented" );
848 * Rerurns whether the file needs to be rendered. Returns true if the
849 * file requires rotation and we are able to rotate it.
854 public function mustRender( $file ) {
855 return self
::canRotate() && $this->getRotation( $file ) != 0;