Merge "Drop zh-tw message "saveprefs""
[lhc/web/wiklou.git] / includes / media / Bitmap.php
1 <?php
2 /**
3 * Generic handler for bitmap images.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup Media
22 */
23
24 /**
25 * Generic handler for bitmap images
26 *
27 * @ingroup Media
28 */
29 class BitmapHandler extends TransformationalImageHandler {
30
31 /**
32 * Returns which scaler type should be used. Creates parent directories
33 * for $dstPath and returns 'client' on error
34 *
35 * @param string $dstPath
36 * @param bool $checkDstPath
37 * @return string|Callable One of client, im, custom, gd, imext or an array( object, method )
38 */
39 protected function getScalerType( $dstPath, $checkDstPath = true ) {
40 global $wgUseImageResize, $wgUseImageMagick, $wgCustomConvertCommand;
41
42 if ( !$dstPath && $checkDstPath ) {
43 # No output path available, client side scaling only
44 $scaler = 'client';
45 } elseif ( !$wgUseImageResize ) {
46 $scaler = 'client';
47 } elseif ( $wgUseImageMagick ) {
48 $scaler = 'im';
49 } elseif ( $wgCustomConvertCommand ) {
50 $scaler = 'custom';
51 } elseif ( function_exists( 'imagecreatetruecolor' ) ) {
52 $scaler = 'gd';
53 } elseif ( class_exists( 'Imagick' ) ) {
54 $scaler = 'imext';
55 } else {
56 $scaler = 'client';
57 }
58
59 return $scaler;
60 }
61
62 /**
63 * Transform an image using ImageMagick
64 *
65 * @param File $image File associated with this thumbnail
66 * @param array $params Array with scaler params
67 *
68 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
69 */
70 protected function transformImageMagick( $image, $params ) {
71 # use ImageMagick
72 global $wgSharpenReductionThreshold, $wgSharpenParameter, $wgMaxAnimatedGifArea,
73 $wgImageMagickTempDir, $wgImageMagickConvertCommand;
74
75 $quality = array();
76 $sharpen = array();
77 $scene = false;
78 $animation_pre = array();
79 $animation_post = array();
80 $decoderHint = array();
81 if ( $params['mimeType'] == 'image/jpeg' ) {
82 $qualityVal = isset( $params['quality'] ) ? (string)$params['quality'] : null;
83 $quality = array( '-quality', $qualityVal ?: '80' ); // 80%
84 # Sharpening, see bug 6193
85 if ( ( $params['physicalWidth'] + $params['physicalHeight'] )
86 / ( $params['srcWidth'] + $params['srcHeight'] )
87 < $wgSharpenReductionThreshold
88 ) {
89 $sharpen = array( '-sharpen', $wgSharpenParameter );
90 }
91 if ( version_compare( $this->getMagickVersion(), "6.5.6" ) >= 0 ) {
92 // JPEG decoder hint to reduce memory, available since IM 6.5.6-2
93 $decoderHint = array( '-define', "jpeg:size={$params['physicalDimensions']}" );
94 }
95 } elseif ( $params['mimeType'] == 'image/png' || $params['mimeType'] == 'image/webp' ) {
96 $quality = array( '-quality', '95' ); // zlib 9, adaptive filtering
97 } elseif ( $params['mimeType'] == 'image/gif' ) {
98 if ( $this->getImageArea( $image ) > $wgMaxAnimatedGifArea ) {
99 // Extract initial frame only; we're so big it'll
100 // be a total drag. :P
101 $scene = 0;
102 } elseif ( $this->isAnimatedImage( $image ) ) {
103 // Coalesce is needed to scale animated GIFs properly (bug 1017).
104 $animation_pre = array( '-coalesce' );
105 // We optimize the output, but -optimize is broken,
106 // use optimizeTransparency instead (bug 11822)
107 if ( version_compare( $this->getMagickVersion(), "6.3.5" ) >= 0 ) {
108 $animation_post = array( '-fuzz', '5%', '-layers', 'optimizeTransparency' );
109 }
110 }
111 } elseif ( $params['mimeType'] == 'image/x-xcf' ) {
112 // Before merging layers, we need to set the background
113 // to be transparent to preserve alpha, as -layers merge
114 // merges all layers on to a canvas filled with the
115 // background colour. After merging we reset the background
116 // to be white for the default background colour setting
117 // in the PNG image (which is used in old IE)
118 $animation_pre = array(
119 '-background', 'transparent',
120 '-layers', 'merge',
121 '-background', 'white',
122 );
123 MediaWiki\suppressWarnings();
124 $xcfMeta = unserialize( $image->getMetadata() );
125 MediaWiki\restoreWarnings();
126 if ( $xcfMeta
127 && isset( $xcfMeta['colorType'] )
128 && $xcfMeta['colorType'] === 'greyscale-alpha'
129 && version_compare( $this->getMagickVersion(), "6.8.9-3" ) < 0
130 ) {
131 // bug 66323 - Greyscale images not rendered properly.
132 // So only take the "red" channel.
133 $channelOnly = array( '-channel', 'R', '-separate' );
134 $animation_pre = array_merge( $animation_pre, $channelOnly );
135 }
136 }
137
138 // Use one thread only, to avoid deadlock bugs on OOM
139 $env = array( 'OMP_NUM_THREADS' => 1 );
140 if ( strval( $wgImageMagickTempDir ) !== '' ) {
141 $env['MAGICK_TMPDIR'] = $wgImageMagickTempDir;
142 }
143
144 $rotation = isset( $params['disableRotation'] ) ? 0 : $this->getRotation( $image );
145 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
146
147 $cmd = call_user_func_array( 'wfEscapeShellArg', array_merge(
148 array( $wgImageMagickConvertCommand ),
149 $quality,
150 // Specify white background color, will be used for transparent images
151 // in Internet Explorer/Windows instead of default black.
152 array( '-background', 'white' ),
153 $decoderHint,
154 array( $this->escapeMagickInput( $params['srcPath'], $scene ) ),
155 $animation_pre,
156 // For the -thumbnail option a "!" is needed to force exact size,
157 // or ImageMagick may decide your ratio is wrong and slice off
158 // a pixel.
159 array( '-thumbnail', "{$width}x{$height}!" ),
160 // Add the source url as a comment to the thumb, but don't add the flag if there's no comment
161 ( $params['comment'] !== ''
162 ? array( '-set', 'comment', $this->escapeMagickProperty( $params['comment'] ) )
163 : array() ),
164 array( '-depth', 8 ),
165 $sharpen,
166 array( '-rotate', "-$rotation" ),
167 $animation_post,
168 array( $this->escapeMagickOutput( $params['dstPath'] ) ) ) );
169
170 wfDebug( __METHOD__ . ": running ImageMagick: $cmd\n" );
171 $retval = 0;
172 $err = wfShellExecWithStderr( $cmd, $retval, $env );
173
174 if ( $retval !== 0 ) {
175 $this->logErrorForExternalProcess( $retval, $err, $cmd );
176
177 return $this->getMediaTransformError( $params, "$err\nError code: $retval" );
178 }
179
180 return false; # No error
181 }
182
183 /**
184 * Transform an image using the Imagick PHP extension
185 *
186 * @param File $image File associated with this thumbnail
187 * @param array $params Array with scaler params
188 *
189 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
190 */
191 protected function transformImageMagickExt( $image, $params ) {
192 global $wgSharpenReductionThreshold, $wgSharpenParameter, $wgMaxAnimatedGifArea;
193
194 try {
195 $im = new Imagick();
196 $im->readImage( $params['srcPath'] );
197
198 if ( $params['mimeType'] == 'image/jpeg' ) {
199 // Sharpening, see bug 6193
200 if ( ( $params['physicalWidth'] + $params['physicalHeight'] )
201 / ( $params['srcWidth'] + $params['srcHeight'] )
202 < $wgSharpenReductionThreshold
203 ) {
204 // Hack, since $wgSharpenParameter is written specifically for the command line convert
205 list( $radius, $sigma ) = explode( 'x', $wgSharpenParameter );
206 $im->sharpenImage( $radius, $sigma );
207 }
208 $qualityVal = isset( $params['quality'] ) ? (string)$params['quality'] : null;
209 $im->setCompressionQuality( $qualityVal ?: 80 );
210 } elseif ( $params['mimeType'] == 'image/png' ) {
211 $im->setCompressionQuality( 95 );
212 } elseif ( $params['mimeType'] == 'image/gif' ) {
213 if ( $this->getImageArea( $image ) > $wgMaxAnimatedGifArea ) {
214 // Extract initial frame only; we're so big it'll
215 // be a total drag. :P
216 $im->setImageScene( 0 );
217 } elseif ( $this->isAnimatedImage( $image ) ) {
218 // Coalesce is needed to scale animated GIFs properly (bug 1017).
219 $im = $im->coalesceImages();
220 }
221 }
222
223 $rotation = isset( $params['disableRotation'] ) ? 0 : $this->getRotation( $image );
224 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
225
226 $im->setImageBackgroundColor( new ImagickPixel( 'white' ) );
227
228 // Call Imagick::thumbnailImage on each frame
229 foreach ( $im as $i => $frame ) {
230 if ( !$frame->thumbnailImage( $width, $height, /* fit */ false ) ) {
231 return $this->getMediaTransformError( $params, "Error scaling frame $i" );
232 }
233 }
234 $im->setImageDepth( 8 );
235
236 if ( $rotation ) {
237 if ( !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) {
238 return $this->getMediaTransformError( $params, "Error rotating $rotation degrees" );
239 }
240 }
241
242 if ( $this->isAnimatedImage( $image ) ) {
243 wfDebug( __METHOD__ . ": Writing animated thumbnail\n" );
244 // This is broken somehow... can't find out how to fix it
245 $result = $im->writeImages( $params['dstPath'], true );
246 } else {
247 $result = $im->writeImage( $params['dstPath'] );
248 }
249 if ( !$result ) {
250 return $this->getMediaTransformError( $params,
251 "Unable to write thumbnail to {$params['dstPath']}" );
252 }
253 } catch ( ImagickException $e ) {
254 return $this->getMediaTransformError( $params, $e->getMessage() );
255 }
256
257 return false;
258 }
259
260 /**
261 * Transform an image using a custom command
262 *
263 * @param File $image File associated with this thumbnail
264 * @param array $params Array with scaler params
265 *
266 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
267 */
268 protected function transformCustom( $image, $params ) {
269 # Use a custom convert command
270 global $wgCustomConvertCommand;
271
272 # Variables: %s %d %w %h
273 $src = wfEscapeShellArg( $params['srcPath'] );
274 $dst = wfEscapeShellArg( $params['dstPath'] );
275 $cmd = $wgCustomConvertCommand;
276 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
277 $cmd = str_replace( '%h', wfEscapeShellArg( $params['physicalHeight'] ),
278 str_replace( '%w', wfEscapeShellArg( $params['physicalWidth'] ), $cmd ) ); # Size
279 wfDebug( __METHOD__ . ": Running custom convert command $cmd\n" );
280 $retval = 0;
281 $err = wfShellExecWithStderr( $cmd, $retval );
282
283 if ( $retval !== 0 ) {
284 $this->logErrorForExternalProcess( $retval, $err, $cmd );
285
286 return $this->getMediaTransformError( $params, $err );
287 }
288
289 return false; # No error
290 }
291
292 /**
293 * Transform an image using the built in GD library
294 *
295 * @param File $image File associated with this thumbnail
296 * @param array $params Array with scaler params
297 *
298 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
299 */
300 protected function transformGd( $image, $params ) {
301 # Use PHP's builtin GD library functions.
302 #
303 # First find out what kind of file this is, and select the correct
304 # input routine for this.
305
306 $typemap = array(
307 'image/gif' => array( 'imagecreatefromgif', 'palette', false, 'imagegif' ),
308 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', true,
309 array( __CLASS__, 'imageJpegWrapper' ) ),
310 'image/png' => array( 'imagecreatefrompng', 'bits', false, 'imagepng' ),
311 'image/vnd.wap.wbmp' => array( 'imagecreatefromwbmp', 'palette', false, 'imagewbmp' ),
312 'image/xbm' => array( 'imagecreatefromxbm', 'palette', false, 'imagexbm' ),
313 );
314
315 if ( !isset( $typemap[$params['mimeType']] ) ) {
316 $err = 'Image type not supported';
317 wfDebug( "$err\n" );
318 $errMsg = wfMessage( 'thumbnail_image-type' )->text();
319
320 return $this->getMediaTransformError( $params, $errMsg );
321 }
322 list( $loader, $colorStyle, $useQuality, $saveType ) = $typemap[$params['mimeType']];
323
324 if ( !function_exists( $loader ) ) {
325 $err = "Incomplete GD library configuration: missing function $loader";
326 wfDebug( "$err\n" );
327 $errMsg = wfMessage( 'thumbnail_gd-library', $loader )->text();
328
329 return $this->getMediaTransformError( $params, $errMsg );
330 }
331
332 if ( !file_exists( $params['srcPath'] ) ) {
333 $err = "File seems to be missing: {$params['srcPath']}";
334 wfDebug( "$err\n" );
335 $errMsg = wfMessage( 'thumbnail_image-missing', $params['srcPath'] )->text();
336
337 return $this->getMediaTransformError( $params, $errMsg );
338 }
339
340 $src_image = call_user_func( $loader, $params['srcPath'] );
341
342 $rotation = function_exists( 'imagerotate' ) && !isset( $params['disableRotation'] ) ? $this->getRotation( $image ) : 0;
343 list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
344 $dst_image = imagecreatetruecolor( $width, $height );
345
346 // Initialise the destination image to transparent instead of
347 // the default solid black, to support PNG and GIF transparency nicely
348 $background = imagecolorallocate( $dst_image, 0, 0, 0 );
349 imagecolortransparent( $dst_image, $background );
350 imagealphablending( $dst_image, false );
351
352 if ( $colorStyle == 'palette' ) {
353 // Don't resample for paletted GIF images.
354 // It may just uglify them, and completely breaks transparency.
355 imagecopyresized( $dst_image, $src_image,
356 0, 0, 0, 0,
357 $width, $height,
358 imagesx( $src_image ), imagesy( $src_image ) );
359 } else {
360 imagecopyresampled( $dst_image, $src_image,
361 0, 0, 0, 0,
362 $width, $height,
363 imagesx( $src_image ), imagesy( $src_image ) );
364 }
365
366 if ( $rotation % 360 != 0 && $rotation % 90 == 0 ) {
367 $rot_image = imagerotate( $dst_image, $rotation, 0 );
368 imagedestroy( $dst_image );
369 $dst_image = $rot_image;
370 }
371
372 imagesavealpha( $dst_image, true );
373
374 $funcParams = array( $dst_image, $params['dstPath'] );
375 if ( $useQuality && isset( $params['quality'] ) ) {
376 $funcParams[] = $params['quality'];
377 }
378 call_user_func_array( $saveType, $funcParams );
379
380 imagedestroy( $dst_image );
381 imagedestroy( $src_image );
382
383 return false; # No error
384 }
385
386 /**
387 * Callback for transformGd when transforming jpeg images.
388 */
389 // FIXME: transformImageMagick() & transformImageMagickExt() uses JPEG quality 80, here it's 95?
390 static function imageJpegWrapper( $dst_image, $thumbPath, $quality = 95 ) {
391 imageinterlace( $dst_image );
392 imagejpeg( $dst_image, $thumbPath, $quality );
393 }
394
395 /**
396 * Returns whether the current scaler supports rotation (im and gd do)
397 *
398 * @return bool
399 */
400 public function canRotate() {
401 $scaler = $this->getScalerType( null, false );
402 switch ( $scaler ) {
403 case 'im':
404 # ImageMagick supports autorotation
405 return true;
406 case 'imext':
407 # Imagick::rotateImage
408 return true;
409 case 'gd':
410 # GD's imagerotate function is used to rotate images, but not
411 # all precompiled PHP versions have that function
412 return function_exists( 'imagerotate' );
413 default:
414 # Other scalers don't support rotation
415 return false;
416 }
417 }
418
419 /**
420 * @see $wgEnableAutoRotation
421 * @return bool Whether auto rotation is enabled
422 */
423 public function autoRotateEnabled() {
424 global $wgEnableAutoRotation;
425
426 if ( $wgEnableAutoRotation === null ) {
427 // Only enable auto-rotation when we actually can
428 return $this->canRotate();
429 }
430
431 return $wgEnableAutoRotation;
432 }
433
434 /**
435 * @param File $file
436 * @param array $params Rotate parameters.
437 * 'rotation' clockwise rotation in degrees, allowed are multiples of 90
438 * @since 1.21
439 * @return bool
440 */
441 public function rotate( $file, $params ) {
442 global $wgImageMagickConvertCommand;
443
444 $rotation = ( $params['rotation'] + $this->getRotation( $file ) ) % 360;
445 $scene = false;
446
447 $scaler = $this->getScalerType( null, false );
448 switch ( $scaler ) {
449 case 'im':
450 $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . " " .
451 wfEscapeShellArg( $this->escapeMagickInput( $params['srcPath'], $scene ) ) .
452 " -rotate " . wfEscapeShellArg( "-$rotation" ) . " " .
453 wfEscapeShellArg( $this->escapeMagickOutput( $params['dstPath'] ) );
454 wfDebug( __METHOD__ . ": running ImageMagick: $cmd\n" );
455 $retval = 0;
456 $err = wfShellExecWithStderr( $cmd, $retval );
457 if ( $retval !== 0 ) {
458 $this->logErrorForExternalProcess( $retval, $err, $cmd );
459
460 return new MediaTransformError( 'thumbnail_error', 0, 0, $err );
461 }
462
463 return false;
464 case 'imext':
465 $im = new Imagick();
466 $im->readImage( $params['srcPath'] );
467 if ( !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) {
468 return new MediaTransformError( 'thumbnail_error', 0, 0,
469 "Error rotating $rotation degrees" );
470 }
471 $result = $im->writeImage( $params['dstPath'] );
472 if ( !$result ) {
473 return new MediaTransformError( 'thumbnail_error', 0, 0,
474 "Unable to write image to {$params['dstPath']}" );
475 }
476
477 return false;
478 default:
479 return new MediaTransformError( 'thumbnail_error', 0, 0,
480 "$scaler rotation not implemented" );
481 }
482 }
483 }