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' );
358 wfSuppressWarnings();
359 $xcfMeta = unserialize( $image->getMetadata() );
362 && isset( $xcfMeta['colorType'] )
363 && $xcfMeta['colorType'] === 'greyscale-alpha'
364 && version_compare( $this->getMagickVersion(), "6.8.9-3" ) < 0
366 // bug 66323 - Greyscale images not rendered properly.
367 // So only take the "red" channel.
368 $channelOnly = array( '-channel', 'R', '-separate' );
369 $animation_post = array_merge( $animation_post, $channelOnly );
373 // Use one thread only, to avoid deadlock bugs on OOM
374 $env = array( 'OMP_NUM_THREADS' => 1 );
375 if ( strval( $wgImageMagickTempDir ) !== '' ) {
376 $env['MAGICK_TMPDIR'] = $wgImageMagickTempDir;
379 $rotation = $this->getRotation( $image );
380 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
382 $cmd = call_user_func_array( 'wfEscapeShellArg', array_merge(
383 array( $wgImageMagickConvertCommand ),
385 // Specify white background color, will be used for transparent images
386 // in Internet Explorer/Windows instead of default black.
387 array( '-background', 'white' ),
389 array( $this->escapeMagickInput( $params['srcPath'], $scene ) ),
391 // For the -thumbnail option a "!" is needed to force exact size,
392 // or ImageMagick may decide your ratio is wrong and slice off
394 array( '-thumbnail', "{$width}x{$height}!" ),
395 // Add the source url as a comment to the thumb, but don't add the flag if there's no comment
396 ( $params['comment'] !== ''
397 ?
array( '-set', 'comment', $this->escapeMagickProperty( $params['comment'] ) )
399 array( '-depth', 8 ),
401 array( '-rotate', "-$rotation" ),
403 array( $this->escapeMagickOutput( $params['dstPath'] ) ) ) );
405 wfDebug( __METHOD__
. ": running ImageMagick: $cmd\n" );
406 wfProfileIn( 'convert' );
408 $err = wfShellExecWithStderr( $cmd, $retval, $env );
409 wfProfileOut( 'convert' );
411 if ( $retval !== 0 ) {
412 $this->logErrorForExternalProcess( $retval, $err, $cmd );
414 return $this->getMediaTransformError( $params, "$err\nError code: $retval" );
417 return false; # No error
421 * Transform an image using the Imagick PHP extension
423 * @param File $image File associated with this thumbnail
424 * @param array $params Array with scaler params
426 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
428 protected function transformImageMagickExt( $image, $params ) {
429 global $wgSharpenReductionThreshold, $wgSharpenParameter, $wgMaxAnimatedGifArea;
433 $im->readImage( $params['srcPath'] );
435 if ( $params['mimeType'] == 'image/jpeg' ) {
436 // Sharpening, see bug 6193
437 if ( ( $params['physicalWidth'] +
$params['physicalHeight'] )
438 / ( $params['srcWidth'] +
$params['srcHeight'] )
439 < $wgSharpenReductionThreshold
441 // Hack, since $wgSharpenParamater is written specifically for the command line convert
442 list( $radius, $sigma ) = explode( 'x', $wgSharpenParameter );
443 $im->sharpenImage( $radius, $sigma );
445 $qualityVal = isset( $params['quality'] ) ?
(string) $params['quality'] : null;
446 $im->setCompressionQuality( $qualityVal ?
: 80 );
447 } elseif ( $params['mimeType'] == 'image/png' ) {
448 $im->setCompressionQuality( 95 );
449 } elseif ( $params['mimeType'] == 'image/gif' ) {
450 if ( $this->getImageArea( $image ) > $wgMaxAnimatedGifArea ) {
451 // Extract initial frame only; we're so big it'll
452 // be a total drag. :P
453 $im->setImageScene( 0 );
454 } elseif ( $this->isAnimatedImage( $image ) ) {
455 // Coalesce is needed to scale animated GIFs properly (bug 1017).
456 $im = $im->coalesceImages();
460 $rotation = $this->getRotation( $image );
461 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
463 $im->setImageBackgroundColor( new ImagickPixel( 'white' ) );
465 // Call Imagick::thumbnailImage on each frame
466 foreach ( $im as $i => $frame ) {
467 if ( !$frame->thumbnailImage( $width, $height, /* fit */ false ) ) {
468 return $this->getMediaTransformError( $params, "Error scaling frame $i" );
471 $im->setImageDepth( 8 );
474 if ( !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) {
475 return $this->getMediaTransformError( $params, "Error rotating $rotation degrees" );
479 if ( $this->isAnimatedImage( $image ) ) {
480 wfDebug( __METHOD__
. ": Writing animated thumbnail\n" );
481 // This is broken somehow... can't find out how to fix it
482 $result = $im->writeImages( $params['dstPath'], true );
484 $result = $im->writeImage( $params['dstPath'] );
487 return $this->getMediaTransformError( $params,
488 "Unable to write thumbnail to {$params['dstPath']}" );
490 } catch ( ImagickException
$e ) {
491 return $this->getMediaTransformError( $params, $e->getMessage() );
498 * Transform an image using a custom command
500 * @param File $image File associated with this thumbnail
501 * @param array $params Array with scaler params
503 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
505 protected function transformCustom( $image, $params ) {
506 # Use a custom convert command
507 global $wgCustomConvertCommand;
509 # Variables: %s %d %w %h
510 $src = wfEscapeShellArg( $params['srcPath'] );
511 $dst = wfEscapeShellArg( $params['dstPath'] );
512 $cmd = $wgCustomConvertCommand;
513 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
514 $cmd = str_replace( '%h', wfEscapeShellArg( $params['physicalHeight'] ),
515 str_replace( '%w', wfEscapeShellArg( $params['physicalWidth'] ), $cmd ) ); # Size
516 wfDebug( __METHOD__
. ": Running custom convert command $cmd\n" );
517 wfProfileIn( 'convert' );
519 $err = wfShellExecWithStderr( $cmd, $retval );
520 wfProfileOut( 'convert' );
522 if ( $retval !== 0 ) {
523 $this->logErrorForExternalProcess( $retval, $err, $cmd );
525 return $this->getMediaTransformError( $params, $err );
528 return false; # No error
532 * Get a MediaTransformError with error 'thumbnail_error'
534 * @param array $params Parameter array as passed to the transform* functions
535 * @param string $errMsg Error message
536 * @return MediaTransformError
538 public function getMediaTransformError( $params, $errMsg ) {
539 return new MediaTransformError( 'thumbnail_error', $params['clientWidth'],
540 $params['clientHeight'], $errMsg );
544 * Transform an image using the built in GD library
546 * @param File $image File associated with this thumbnail
547 * @param array $params Array with scaler params
549 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
551 protected function transformGd( $image, $params ) {
552 # Use PHP's builtin GD library functions.
554 # First find out what kind of file this is, and select the correct
555 # input routine for this.
558 'image/gif' => array( 'imagecreatefromgif', 'palette', false, 'imagegif' ),
559 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', true,
560 array( __CLASS__
, 'imageJpegWrapper' ) ),
561 'image/png' => array( 'imagecreatefrompng', 'bits', false, 'imagepng' ),
562 'image/vnd.wap.wbmp' => array( 'imagecreatefromwbmp', 'palette', false, 'imagewbmp' ),
563 'image/xbm' => array( 'imagecreatefromxbm', 'palette', false, 'imagexbm' ),
566 if ( !isset( $typemap[$params['mimeType']] ) ) {
567 $err = 'Image type not supported';
569 $errMsg = wfMessage( 'thumbnail_image-type' )->text();
571 return $this->getMediaTransformError( $params, $errMsg );
573 list( $loader, $colorStyle, $useQuality, $saveType ) = $typemap[$params['mimeType']];
575 if ( !function_exists( $loader ) ) {
576 $err = "Incomplete GD library configuration: missing function $loader";
578 $errMsg = wfMessage( 'thumbnail_gd-library', $loader )->text();
580 return $this->getMediaTransformError( $params, $errMsg );
583 if ( !file_exists( $params['srcPath'] ) ) {
584 $err = "File seems to be missing: {$params['srcPath']}";
586 $errMsg = wfMessage( 'thumbnail_image-missing', $params['srcPath'] )->text();
588 return $this->getMediaTransformError( $params, $errMsg );
591 $src_image = call_user_func( $loader, $params['srcPath'] );
593 $rotation = function_exists( 'imagerotate' ) ?
$this->getRotation( $image ) : 0;
594 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
595 $dst_image = imagecreatetruecolor( $width, $height );
597 // Initialise the destination image to transparent instead of
598 // the default solid black, to support PNG and GIF transparency nicely
599 $background = imagecolorallocate( $dst_image, 0, 0, 0 );
600 imagecolortransparent( $dst_image, $background );
601 imagealphablending( $dst_image, false );
603 if ( $colorStyle == 'palette' ) {
604 // Don't resample for paletted GIF images.
605 // It may just uglify them, and completely breaks transparency.
606 imagecopyresized( $dst_image, $src_image,
609 imagesx( $src_image ), imagesy( $src_image ) );
611 imagecopyresampled( $dst_image, $src_image,
614 imagesx( $src_image ), imagesy( $src_image ) );
617 if ( $rotation %
360 != 0 && $rotation %
90 == 0 ) {
618 $rot_image = imagerotate( $dst_image, $rotation, 0 );
619 imagedestroy( $dst_image );
620 $dst_image = $rot_image;
623 imagesavealpha( $dst_image, true );
625 $funcParams = array( $dst_image, $params['dstPath'] );
626 if ( $useQuality && isset( $params['quality'] ) ) {
627 $funcParams[] = $params['quality'];
629 call_user_func_array( $saveType, $funcParams );
631 imagedestroy( $dst_image );
632 imagedestroy( $src_image );
634 return false; # No error
638 * Escape a string for ImageMagick's property input (e.g. -set -comment)
639 * See InterpretImageProperties() in magick/property.c
643 function escapeMagickProperty( $s ) {
644 // Double the backslashes
645 $s = str_replace( '\\', '\\\\', $s );
646 // Double the percents
647 $s = str_replace( '%', '%%', $s );
648 // Escape initial - or @
649 if ( strlen( $s ) > 0 && ( $s[0] === '-' ||
$s[0] === '@' ) ) {
657 * Escape a string for ImageMagick's input filenames. See ExpandFilenames()
658 * and GetPathComponent() in magick/utility.c.
660 * This won't work with an initial ~ or @, so input files should be prefixed
661 * with the directory name.
663 * Glob character unescaping is broken in ImageMagick before 6.6.1-5, but
664 * it's broken in a way that doesn't involve trying to convert every file
665 * in a directory, so we're better off escaping and waiting for the bugfix
666 * to filter down to users.
668 * @param string $path The file path
669 * @param bool|string $scene The scene specification, or false if there is none
670 * @throws MWException
673 function escapeMagickInput( $path, $scene = false ) {
674 # Die on initial metacharacters (caller should prepend path)
675 $firstChar = substr( $path, 0, 1 );
676 if ( $firstChar === '~' ||
$firstChar === '@' ) {
677 throw new MWException( __METHOD__
. ': cannot escape this path name' );
681 $path = preg_replace( '/[*?\[\]{}]/', '\\\\\0', $path );
683 return $this->escapeMagickPath( $path, $scene );
687 * Escape a string for ImageMagick's output filename. See
688 * InterpretImageFilename() in magick/image.c.
689 * @param string $path The file path
690 * @param bool|string $scene The scene specification, or false if there is none
693 function escapeMagickOutput( $path, $scene = false ) {
694 $path = str_replace( '%', '%%', $path );
696 return $this->escapeMagickPath( $path, $scene );
700 * Armour a string against ImageMagick's GetPathComponent(). This is a
701 * helper function for escapeMagickInput() and escapeMagickOutput().
703 * @param string $path The file path
704 * @param bool|string $scene The scene specification, or false if there is none
705 * @throws MWException
708 protected function escapeMagickPath( $path, $scene = false ) {
709 # Die on format specifiers (other than drive letters). The regex is
710 # meant to match all the formats you get from "convert -list format"
711 if ( preg_match( '/^([a-zA-Z0-9-]+):/', $path, $m ) ) {
712 if ( wfIsWindows() && is_dir( $m[0] ) ) {
713 // OK, it's a drive letter
714 // ImageMagick has a similar exception, see IsMagickConflict()
716 throw new MWException( __METHOD__
. ': unexpected colon character in path name' );
720 # If there are square brackets, add a do-nothing scene specification
721 # to force a literal interpretation
722 if ( $scene === false ) {
723 if ( strpos( $path, '[' ) !== false ) {
734 * Retrieve the version of the installed ImageMagick
735 * You can use PHPs version_compare() to use this value
736 * Value is cached for one hour.
737 * @return string Representing the IM version.
739 protected function getMagickVersion() {
742 $cache = $wgMemc->get( "imagemagick-version" );
744 global $wgImageMagickConvertCommand;
745 $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . ' -version';
746 wfDebug( __METHOD__
. ": Running convert -version\n" );
748 $return = wfShellExec( $cmd, $retval );
749 $x = preg_match( '/Version: ImageMagick ([0-9]*\.[0-9]*\.[0-9]*)/', $return, $matches );
751 wfDebug( __METHOD__
. ": ImageMagick version check failed\n" );
755 $wgMemc->set( "imagemagick-version", $matches[1], 3600 );
763 // FIXME: transformImageMagick() & transformImageMagickExt() uses JPEG quality 80, here it's 95?
764 static function imageJpegWrapper( $dst_image, $thumbPath, $quality = 95 ) {
765 imageinterlace( $dst_image );
766 imagejpeg( $dst_image, $thumbPath, $quality );
770 * Returns whether the current scaler supports rotation (im and gd do)
774 public static function canRotate() {
775 $scaler = self
::getScalerType( null, false );
778 # ImageMagick supports autorotation
781 # Imagick::rotateImage
784 # GD's imagerotate function is used to rotate images, but not
785 # all precompiled PHP versions have that function
786 return function_exists( 'imagerotate' );
788 # Other scalers don't support rotation
794 * @see $wgEnableAutoRotation
795 * @return bool Whether auto rotation is enabled
797 public static function autoRotateEnabled() {
798 global $wgEnableAutoRotation;
800 if ( $wgEnableAutoRotation === null ) {
801 // Only enable auto-rotation when the bitmap handler can rotate
802 $wgEnableAutoRotation = BitmapHandler
::canRotate();
805 return $wgEnableAutoRotation;
810 * @param array $params Rotate parameters.
811 * 'rotation' clockwise rotation in degrees, allowed are multiples of 90
815 public function rotate( $file, $params ) {
816 global $wgImageMagickConvertCommand;
818 $rotation = ( $params['rotation'] +
$this->getRotation( $file ) ) %
360;
821 $scaler = self
::getScalerType( null, false );
824 $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . " " .
825 wfEscapeShellArg( $this->escapeMagickInput( $params['srcPath'], $scene ) ) .
826 " -rotate " . wfEscapeShellArg( "-$rotation" ) . " " .
827 wfEscapeShellArg( $this->escapeMagickOutput( $params['dstPath'] ) );
828 wfDebug( __METHOD__
. ": running ImageMagick: $cmd\n" );
829 wfProfileIn( 'convert' );
831 $err = wfShellExecWithStderr( $cmd, $retval );
832 wfProfileOut( 'convert' );
833 if ( $retval !== 0 ) {
834 $this->logErrorForExternalProcess( $retval, $err, $cmd );
836 return new MediaTransformError( 'thumbnail_error', 0, 0, $err );
842 $im->readImage( $params['srcPath'] );
843 if ( !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) {
844 return new MediaTransformError( 'thumbnail_error', 0, 0,
845 "Error rotating $rotation degrees" );
847 $result = $im->writeImage( $params['dstPath'] );
849 return new MediaTransformError( 'thumbnail_error', 0, 0,
850 "Unable to write image to {$params['dstPath']}" );
855 return new MediaTransformError( 'thumbnail_error', 0, 0,
856 "$scaler rotation not implemented" );
861 * Rerurns whether the file needs to be rendered. Returns true if the
862 * file requires rotation and we are able to rotate it.
867 public function mustRender( $file ) {
868 return self
::canRotate() && $this->getRotation( $file ) != 0;