3 * Handler for JPEG 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
24 use MediaWiki\Shell\Shell
;
27 * JPEG specific handler.
28 * Inherits most stuff from BitmapHandler, just here to do the metadata handler differently.
30 * Metadata stuff common to Jpeg and built-in Tiff (not PagedTiffHandler) is
31 * in ExifBitmapHandler.
35 class JpegHandler
extends ExifBitmapHandler
{
36 const SRGB_EXIF_COLOR_SPACE
= 'sRGB';
37 const SRGB_ICC_PROFILE_DESCRIPTION
= 'sRGB IEC61966-2.1';
39 public function normaliseParams( $image, &$params ) {
40 if ( !parent
::normaliseParams( $image, $params ) ) {
43 if ( isset( $params['quality'] ) && !self
::validateQuality( $params['quality'] ) ) {
49 public function validateParam( $name, $value ) {
50 if ( $name === 'quality' ) {
51 return self
::validateQuality( $value );
53 return parent
::validateParam( $name, $value );
57 /** Validate and normalize quality value to be between 1 and 100 (inclusive).
58 * @param int $value Quality value, will be converted to integer or 0 if invalid
59 * @return bool True if the value is valid
61 private static function validateQuality( $value ) {
62 return $value === 'low';
65 public function makeParamString( $params ) {
66 // Prepend quality as "qValue-". This has to match parseParamString() below
67 $res = parent
::makeParamString( $params );
68 if ( $res && isset( $params['quality'] ) ) {
69 $res = "q{$params['quality']}-$res";
74 public function parseParamString( $str ) {
75 // $str contains "qlow-200px" or "200px" strings because thumb.php would strip the filename
76 // first - check if the string begins with "qlow-", and if so, treat it as quality.
77 // Pass the first portion, or the whole string if "qlow-" not found, to the parent
78 // The parsing must match the makeParamString() above
81 if ( preg_match( '/q([^-]+)-(.*)$/', $str, $m ) ) {
83 if ( self
::validateQuality( $v ) ) {
84 $res = parent
::parseParamString( $m[2] );
90 $res = parent
::parseParamString( $str );
95 protected function getScriptParams( $params ) {
96 $res = parent
::getScriptParams( $params );
97 if ( isset( $params['quality'] ) ) {
98 $res['quality'] = $params['quality'];
103 public function getMetadata( $image, $filename ) {
105 $meta = BitmapMetadataHandler
::Jpeg( $filename );
106 if ( !is_array( $meta ) ) {
107 // This should never happen, but doesn't hurt to be paranoid.
108 throw new MWException( 'Metadata array is not an array' );
110 $meta['MEDIAWIKI_EXIF_VERSION'] = Exif
::version();
112 return serialize( $meta );
113 } catch ( Exception
$e ) {
114 // BitmapMetadataHandler throws an exception in certain exceptional
115 // cases like if file does not exist.
116 wfDebug( __METHOD__
. ': ' . $e->getMessage() . "\n" );
118 /* This used to use 0 (ExifBitmapHandler::OLD_BROKEN_FILE) for the cases
119 * * No metadata in the file
120 * * Something is broken in the file.
121 * However, if the metadata support gets expanded then you can't tell if the 0 is from
122 * a broken file, or just no props found. A broken file is likely to stay broken, but
123 * a file which had no props could have props once the metadata support is improved.
124 * Thus switch to using -1 to denote only a broken file, and use an array with only
125 * MEDIAWIKI_EXIF_VERSION to denote no props.
128 return ExifBitmapHandler
::BROKEN_FILE
;
134 * @param array $params Rotate parameters.
135 * 'rotation' clockwise rotation in degrees, allowed are multiples of 90
137 * @return bool|MediaTransformError
139 public function rotate( $file, $params ) {
142 $rotation = ( $params['rotation'] +
$this->getRotation( $file ) ) %
360;
144 if ( $wgJpegTran && is_executable( $wgJpegTran ) ) {
145 $command = Shell
::command( $wgJpegTran,
155 if ( $result->getExitCode() !== 0 ) {
156 $this->logErrorForExternalProcess( $result->getExitCode(),
157 $result->getStdout(),
161 return new MediaTransformError( 'thumbnail_error', 0, 0, $result->getStdout() );
166 return parent
::rotate( $file, $params );
170 public function supportsBucketing() {
174 public function sanitizeParamsForBucketing( $params ) {
175 $params = parent
::sanitizeParamsForBucketing( $params );
177 // Quality needs to be cleared for bucketing. Buckets need to be default quality
178 if ( isset( $params['quality'] ) ) {
179 unset( $params['quality'] );
188 protected function transformImageMagick( $image, $params ) {
189 global $wgUseTinyRGBForJPGThumbnails;
191 $ret = parent
::transformImageMagick( $image, $params );
197 if ( $wgUseTinyRGBForJPGThumbnails ) {
198 // T100976 If the profile embedded in the JPG is sRGB, swap it for the smaller
199 // (and free) TinyRGB
202 * We'll want to replace the color profile for JPGs:
203 * * in the sRGB color space, or with the sRGB profile
204 * (other profiles will be left untouched)
205 * * without color space or profile, in which case browsers
206 * should assume sRGB, but don't always do (e.g. on wide-gamut
207 * monitors (unless it's meant for low bandwith)
208 * @see https://phabricator.wikimedia.org/T134498
210 $colorSpaces = [ self
::SRGB_EXIF_COLOR_SPACE
, '-' ];
211 $profiles = [ self
::SRGB_ICC_PROFILE_DESCRIPTION
];
213 // we'll also add TinyRGB profile to images lacking a profile, but
214 // only if they're not low quality (which are meant to save bandwith
215 // and we don't want to increase the filesize by adding a profile)
216 if ( isset( $params['quality'] ) && $params['quality'] > 30 ) {
220 $this->swapICCProfile(
224 realpath( __DIR__
) . '/tinyrgb.icc'
232 * Swaps an embedded ICC profile for another, if found.
233 * Depends on exiftool, no-op if not installed.
234 * @param string $filepath File to be manipulated (will be overwritten)
235 * @param array $colorSpaces Only process files with this/these Color Space(s)
236 * @param array $oldProfileStrings Exact name(s) of color profile to look for
237 * (the one that will be replaced)
238 * @param string $profileFilepath ICC profile file to apply to the file
242 public function swapICCProfile( $filepath, array $colorSpaces,
243 array $oldProfileStrings, $profileFilepath
247 if ( !$wgExiftool ||
!is_executable( $wgExiftool ) ) {
251 $result = Shell
::command(
254 '-ICC_Profile:ProfileDescription',
262 // Explode EXIF data into an array with [0 => Color Space, 1 => Device Model Desc]
263 $data = explode( "\t", trim( $result->getStdout() ) );
265 if ( $result->getExitCode() !== 0 ) {
269 // Make a regex out of the source data to match it to an array of color
270 // spaces in a case-insensitive way
271 $colorSpaceRegex = '/' . preg_quote( $data[0], '/' ) . '/i';
272 if ( empty( preg_grep( $colorSpaceRegex, $colorSpaces ) ) ) {
273 // We can't establish that this file matches the color space, don't process it
277 $profileRegex = '/' . preg_quote( $data[1], '/' ) . '/i';
278 if ( empty( preg_grep( $profileRegex, $oldProfileStrings ) ) ) {
279 // We can't establish that this file has the expected ICC profile, don't process it
283 $command = Shell
::command( $wgExiftool,
284 '-overwrite_original',
285 '-icc_profile<=' . $profileFilepath,
292 if ( $result->getExitCode() !== 0 ) {
293 $this->logErrorForExternalProcess( $result->getExitCode(),
294 $result->getStdout(),