e573e23737b816c56d719e3a36fdd816a2225394
10 class BitmapHandler
extends ImageHandler
{
12 * Override parent method to add crop to param map.
14 public function getParamMap() {
16 'img_width' => 'width',
22 * Override param map to validate the crop param.
24 public function validateParam( $name, $value ) {
25 if ( $name == 'crop' ) {
26 return $this->splitCropParam( $value ) !== false;
28 return parent
::validateParam( $name, $value );
32 * Split the crop param into up to 4 parts and convert them to integers.
33 * Returns false in case of malformed param.
35 protected function splitCropParam( $value ) {
36 $parts = explode( 'x', $value );
37 if ( count( $parts ) > 4 )
39 foreach ( $parts as &$part ) {
40 $intVal = intval( $part );
41 if ( $intVal === 0 && !( $part === '0' ||
$part === '' ) )
53 * Override parent method to check for optional crop parameter in param
56 public function parseParamString( $str ) {
57 $res = parent
::parseParamString( $str );
58 if ( $res === false ) {
60 if ( preg_match( '/^(\d+)px-([x0-9])crop$/', $str, $m ) ) {
61 return array( 'width' => $m[1], 'crop' => $m[2] );
68 * Add the crop parameter the string generated by the parent.
70 public function makeParamString( $params ) {
71 $res = parent
::makeParamString( $params );
72 if ( !empty( $params['crop'] ) )
73 $res .= '-'.implode( 'x', $params['crop'] ).'crop';
77 public function normaliseParams( $image, &$params ) {
78 global $wgMaxImageArea;
79 # Parent fills in width, height and page and normalizes them.
80 if ( !parent
::normaliseParams( $image, $params ) ) {
84 $mimeType = $image->getMimeType();
85 $srcWidth = $image->getWidth( $params['page'] );
86 $srcHeight = $image->getHeight( $params['page'] );
88 # Don't thumbnail an image so big that it will fill hard drives and send servers into swap
89 # JPEG has the handy property of allowing thumbnailing without full decompression, so we make
90 # an exception for it.
91 if ( $mimeType !== 'image/jpeg' &&
92 $this->getImageArea( $image, $srcWidth, $srcHeight ) > $wgMaxImageArea )
97 # Don't make an image bigger than the source
98 $params['physicalWidth'] = $params['width'];
99 $params['physicalHeight'] = $params['height'];
101 if ( $params['physicalWidth'] >= $srcWidth ) {
102 $params['physicalWidth'] = $srcWidth;
103 $params['physicalHeight'] = $srcHeight;
107 # Validate crop params
108 if ( isset( $params['crop'] ) ) {
109 # $cropParams = array( x, y, width, height );
110 $cropParams = $this->splitCropParam( $params['crop'] );
112 switch ( count( $cropParams ) ) {
117 $cropParams[2] = $srcWidth - $cropParams[0];
119 $cropParams[3] = $srcHeight - $cropParams[1];
121 $cx = $cropParams[0] +
$cropParams[2];
122 $cy = $cropParams[1] +
$cropParams[3];
123 $targetWidth = $cropParams[2];
124 $targetHeight = $cropParams[3];
125 # Can't go outside image
126 if ( $cx > $srcWidth ||
$cy > $srcHeight ) {
127 # TODO: Maybe should fail gracefully?
130 if ( $targetWidth == $srcWidth && $targetHeight == $srcHeight )
133 $params['crop'] = false;
137 $params['crop'] = $cropParams;
138 $params['height'] = $params['physicalHeight'] = File
::scaleHeight(
139 $targetWidth, $targetHeight, $params['width'] );
142 $params['crop'] = false;
150 * Function that returns the number of pixels to be thumbnailed.
151 * Intended for animated GIFs to multiply by the number of frames.
153 protected function getImageArea( $image, $width, $height ) {
154 return $width * $height;
157 public function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
158 global $wgUseImageMagick, $wgImageMagickConvertCommand, $wgImageMagickTempDir;
159 global $wgCustomConvertCommand, $wgUseImageResize;
160 global $wgSharpenParameter, $wgSharpenReductionThreshold;
161 global $wgMaxAnimatedGifArea;
163 if ( !$this->normaliseParams( $image, $params ) ) {
164 return new TransformParameterError( $params );
166 $physicalWidth = $params['physicalWidth'];
167 $physicalHeight = $params['physicalHeight'];
168 $clientWidth = $params['width'];
169 $clientHeight = $params['height'];
170 $srcWidth = $image->getWidth();
171 $srcHeight = $image->getHeight();
172 $mimeType = $image->getMimeType();
173 $srcPath = $image->getPath();
175 wfDebug( __METHOD__
.": creating {$physicalWidth}x{$physicalHeight} thumbnail at $dstPath\n" );
177 if ( !$image->mustRender() && $physicalWidth == $srcWidth && $physicalHeight == $srcHeight ) {
178 # normaliseParams (or the user) wants us to return the unscaled image
179 wfDebug( __METHOD__
.": returning unscaled image\n" );
180 return new ThumbnailImage( $image, $image->getURL(), $clientWidth, $clientHeight, $srcPath );
184 // No output path available, client side scaling only
186 } elseif( !$wgUseImageResize ) {
188 } elseif ( $wgUseImageMagick ) {
190 } elseif ( $wgCustomConvertCommand ) {
192 } elseif ( function_exists( 'imagecreatetruecolor' ) ) {
197 wfDebug( __METHOD__
.": scaler $scaler\n" );
199 if ( $scaler == 'client' ) {
200 # Client-side image scaling, use the source URL
201 # Using the destination URL in a TRANSFORM_LATER request would be incorrect
202 return new ThumbnailImage( $image, $image->getURL(), $clientWidth, $clientHeight, $srcPath );
205 if ( $flags & self
::TRANSFORM_LATER
) {
206 wfDebug( __METHOD__
.": Transforming later per flags.\n" );
207 return new ThumbnailImage( $image, $dstUrl, $clientWidth, $clientHeight, $dstPath );
210 if ( !wfMkdirParents( dirname( $dstPath ) ) ) {
211 wfDebug( __METHOD__
.": Unable to create thumbnail destination directory, falling back to client scaling\n" );
212 return new ThumbnailImage( $image, $image->getURL(), $clientWidth, $clientHeight, $srcPath );
215 if ( $scaler == 'im' ) {
222 if ( $mimeType == 'image/jpeg' ) {
223 $quality = "-quality 80"; // 80%
224 # Sharpening, see bug 6193
225 if ( ( $physicalWidth +
$physicalHeight ) / ( $srcWidth +
$srcHeight ) < $wgSharpenReductionThreshold ) {
226 $sharpen = "-sharpen " . wfEscapeShellArg( $wgSharpenParameter );
228 } elseif ( $mimeType == 'image/png' ) {
229 $quality = "-quality 95"; // zlib 9, adaptive filtering
230 } elseif( $mimeType == 'image/gif' ) {
231 if( $srcWidth * $srcHeight > $wgMaxAnimatedGifArea ) {
232 // Extract initial frame only; we're so big it'll
233 // be a total drag. :P
236 // Coalesce is needed to scale animated GIFs properly (bug 1017).
237 $animation = ' -coalesce ';
241 if ( strval( $wgImageMagickTempDir ) !== '' ) {
242 $tempEnv = 'MAGICK_TMPDIR=' . wfEscapeShellArg( $wgImageMagickTempDir ) . ' ';
247 if ( $params['crop'] ) {
248 $crop = $params['crop'];
249 $cropCmd = "-crop {$crop[2]}x{$crop[3]}+{$crop[0]}+{$crop[1]}";
254 # Specify white background color, will be used for transparent images
255 # in Internet Explorer/Windows instead of default black.
257 # Note, we specify "-size {$physicalWidth}" and NOT "-size {$physicalWidth}x{$physicalHeight}".
258 # It seems that ImageMagick has a bug wherein it produces thumbnails of
259 # the wrong size in the second case.
263 wfEscapeShellArg($wgImageMagickConvertCommand) .
264 " {$cropCmd} {$quality} -background white -size {$physicalWidth} ".
265 wfEscapeShellArg($srcPath . $frame) .
267 // For the -resize option a "!" is needed to force exact size,
268 // or ImageMagick may decide your ratio is wrong and slice off
270 " -thumbnail " . wfEscapeShellArg( "{$physicalWidth}x{$physicalHeight}!" ) .
271 " -depth 8 $sharpen " .
272 wfEscapeShellArg($dstPath) . " 2>&1";
273 wfDebug( __METHOD__
.": running ImageMagick: $cmd\n");
274 wfProfileIn( 'convert' );
275 $err = wfShellExec( $cmd, $retval );
276 wfProfileOut( 'convert' );
277 } elseif( $scaler == 'custom' ) {
278 # Use a custom convert command
279 # Variables: %s %d %w %h
280 $src = wfEscapeShellArg( $srcPath );
281 $dst = wfEscapeShellArg( $dstPath );
282 $cmd = $wgCustomConvertCommand;
283 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
284 $cmd = str_replace( '%h', $physicalHeight, str_replace( '%w', $physicalWidth, $cmd ) ); # Size
285 wfDebug( __METHOD__
.": Running custom convert command $cmd\n" );
286 wfProfileIn( 'convert' );
287 $err = wfShellExec( $cmd, $retval );
288 wfProfileOut( 'convert' );
289 } else /* $scaler == 'gd' */ {
290 # Use PHP's builtin GD library functions.
292 # First find out what kind of file this is, and select the correct
293 # input routine for this.
296 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
297 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( __CLASS__
, 'imageJpegWrapper' ) ),
298 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
299 'image/vnd.wap.wbmp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
300 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
302 if( !isset( $typemap[$mimeType] ) ) {
303 $err = 'Image type not supported';
305 $errMsg = wfMsg ( 'thumbnail_image-type' );
306 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $errMsg );
308 list( $loader, $colorStyle, $saveType ) = $typemap[$mimeType];
310 if( !function_exists( $loader ) ) {
311 $err = "Incomplete GD library configuration: missing function $loader";
313 $errMsg = wfMsg ( 'thumbnail_gd-library', $loader );
314 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $errMsg );
317 if ( !file_exists( $srcPath ) ) {
318 $err = "File seems to be missing: $srcPath";
320 $errMsg = wfMsg ( 'thumbnail_image-missing', $srcPath );
321 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $errMsg );
324 $src_image = call_user_func( $loader, $srcPath );
325 $dst_image = imagecreatetruecolor( $physicalWidth, $physicalHeight );
327 // Initialise the destination image to transparent instead of
328 // the default solid black, to support PNG and GIF transparency nicely
329 $background = imagecolorallocate( $dst_image, 0, 0, 0 );
330 imagecolortransparent( $dst_image, $background );
331 imagealphablending( $dst_image, false );
333 if( $colorStyle == 'palette' ) {
334 // Don't resample for paletted GIF images.
335 // It may just uglify them, and completely breaks transparency.
336 imagecopyresized( $dst_image, $src_image,
338 $physicalWidth, $physicalHeight, imagesx( $src_image ), imagesy( $src_image ) );
340 imagecopyresampled( $dst_image, $src_image,
342 $physicalWidth, $physicalHeight, imagesx( $src_image ), imagesy( $src_image ) );
345 imagesavealpha( $dst_image, true );
347 call_user_func( $saveType, $dst_image, $dstPath );
348 imagedestroy( $dst_image );
349 imagedestroy( $src_image );
353 $removed = $this->removeBadFile( $dstPath, $retval );
354 if ( $retval != 0 ||
$removed ) {
355 wfDebugLog( 'thumbnail',
356 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
357 wfHostname(), $retval, trim($err), $cmd ) );
358 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $err );
360 return new ThumbnailImage( $image, $dstUrl, $clientWidth, $clientHeight, $dstPath );
364 public static function imageJpegWrapper( $dst_image, $thumbPath ) {
365 imageinterlace( $dst_image );
366 imagejpeg( $dst_image, $thumbPath, 95 );
370 public function getMetadata( $image, $filename ) {
372 if( $wgShowEXIF && file_exists( $filename ) ) {
373 $exif = new Exif( $filename );
374 $data = $exif->getFilteredData();
376 $data['MEDIAWIKI_EXIF_VERSION'] = Exif
::version();
377 return serialize( $data );
386 public function getMetadataType( $image ) {
390 public function isMetadataValid( $image, $metadata ) {
392 if ( !$wgShowEXIF ) {
393 # Metadata disabled and so an empty field is expected
396 if ( $metadata === '0' ) {
397 # Special value indicating that there is no EXIF data in the file
400 $exif = @unserialize
( $metadata );
401 if ( !isset( $exif['MEDIAWIKI_EXIF_VERSION'] ) ||
402 $exif['MEDIAWIKI_EXIF_VERSION'] != Exif
::version() )
405 wfDebug( __METHOD__
.": wrong version\n" );
412 * Get a list of EXIF metadata items which should be displayed when
413 * the metadata table is collapsed.
415 * @return array of strings
418 public function visibleMetadataFields() {
420 $lines = explode( "\n", wfMsgForContent( 'metadata-fields' ) );
421 foreach( $lines as $line ) {
423 if( preg_match( '/^\\*\s*(.*?)\s*$/', $line, $matches ) ) {
424 $fields[] = $matches[1];
427 $fields = array_map( 'strtolower', $fields );
431 public function formatMetadata( $image ) {
433 'visible' => array(),
434 'collapsed' => array()
436 $metadata = $image->getMetadata();
440 $exif = unserialize( $metadata );
444 unset( $exif['MEDIAWIKI_EXIF_VERSION'] );
445 $format = new FormatExif( $exif );
447 $formatted = $format->getFormattedData();
448 // Sort fields into visible and collapsed
449 $visibleFields = $this->visibleMetadataFields();
450 foreach ( $formatted as $name => $value ) {
451 $tag = strtolower( $name );
452 self
::addMeta( $result,
453 in_array( $tag, $visibleFields ) ?
'visible' : 'collapsed',