3 * StatusNet, the distributed open-source microblogging tool
5 * Abstraction for an image file
9 * LICENCE: This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU Affero General Public License as published by
11 * the Free Software Foundation, either version 3 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU Affero General Public License for more details.
19 * You should have received a copy of the GNU Affero General Public License
20 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 * @author Evan Prodromou <evan@status.net>
25 * @author Zach Copley <zach@status.net>
26 * @copyright 2008-2009 StatusNet, Inc.
27 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
28 * @link http://status.net/
31 if (!defined('GNUSOCIAL')) { exit(1); }
34 * A wrapper on uploaded files
36 * Makes it slightly easier to accept an image file from upload.
40 * @author Evan Prodromou <evan@status.net>
41 * @author Zach Copley <zach@status.net>
42 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
43 * @link http://status.net/
54 var $rotate=0; // degrees to rotate for properly oriented image (extrapolated from EXIF etc.)
55 var $animated = null; // Animated image? (has more than 1 frame). null means untested
57 function __construct($id=null, $filepath=null, $type=null, $width=null, $height=null)
60 $this->filepath = $filepath;
61 $this->filename = basename($filepath);
63 $info = @getimagesize($this->filepath);
66 ($info[2] == IMAGETYPE_GIF && !function_exists('imagecreatefromgif')) ||
67 ($info[2] == IMAGETYPE_JPEG && !function_exists('imagecreatefromjpeg')) ||
68 ($info[2] == IMAGETYPE_WBMP && !function_exists('imagecreatefromwbmp')) ||
69 ($info[2] == IMAGETYPE_XBM && !function_exists('imagecreatefromxbm')) ||
70 ($info[2] == IMAGETYPE_PNG && !function_exists('imagecreatefrompng'))) {
72 // TRANS: Exception thrown when trying to upload an unsupported image file format.
73 throw new UnsupportedMediaException(_('Unsupported image format.'), $this->filepath);
76 $this->type = ($info) ? $info[2]:$type;
77 $this->width = ($info) ? $info[0]:$width;
78 $this->height = ($info) ? $info[1]:$height;
80 if ($this->type == IMAGETYPE_JPEG && function_exists('exif_read_data')) {
81 // Orientation value to rotate thumbnails properly
82 $exif = exif_read_data($this->filepath);
83 if (is_array($exif) && isset($exif['Orientation'])) {
84 switch ((int)$exif['Orientation']) {
88 case 3: // top is bottom
91 case 6: // top is right
94 case 8: // top is left
98 // If we ever write this back, Orientation should be set to '1'
100 } elseif ($this->type === IMAGETYPE_GIF) {
101 $this->animated = $this->isAnimatedGif();
104 Event::handle('FillImageFileMetadata', array($this));
107 public static function fromFileObject(File $file)
110 $media = common_get_mime_media($file->mimetype);
111 if (Event::handle('CreateFileImageThumbnailSource', array($file, &$imgPath, $media))) {
112 if (empty($file->filename)) {
113 throw new UnsupportedMediaException(_('File without filename could not get a thumbnail source.'));
117 $imgPath = $file->getPath();
120 throw new UnsupportedMediaException(_('Unsupported media format.'), $file->getPath());
124 if (!file_exists($imgPath)) {
125 throw new ServerException(sprintf('Image not available locally: %s', $imgPath));
129 $image = new ImageFile($file->id, $imgPath);
130 } catch (UnsupportedMediaException $e) {
131 // Avoid deleting the original
132 if ($imgPath != $file->getPath()) {
140 public function getPath()
142 if (!file_exists($this->filepath)) {
143 throw new ServerException('No file in ImageFile filepath');
146 return $this->filepath;
149 static function fromUpload($param='upload')
151 switch ($_FILES[$param]['error']) {
152 case UPLOAD_ERR_OK: // success, jump out
155 case UPLOAD_ERR_INI_SIZE:
156 case UPLOAD_ERR_FORM_SIZE:
157 // TRANS: Exception thrown when too large a file is uploaded.
158 // TRANS: %s is the maximum file size, for example "500b", "10kB" or "2MB".
159 throw new Exception(sprintf(_('That file is too big. The maximum file size is %s.'), ImageFile::maxFileSize()));
161 case UPLOAD_ERR_PARTIAL:
162 @unlink($_FILES[$param]['tmp_name']);
163 // TRANS: Exception thrown when uploading an image and that action could not be completed.
164 throw new Exception(_('Partial upload.'));
166 case UPLOAD_ERR_NO_FILE:
167 // No file; probably just a non-AJAX submission.
169 common_log(LOG_ERR, __METHOD__ . ": Unknown upload error " . $_FILES[$param]['error']);
170 // TRANS: Exception thrown when uploading an image fails for an unknown reason.
171 throw new Exception(_('System error uploading file.'));
174 $info = @getimagesize($_FILES[$param]['tmp_name']);
177 @unlink($_FILES[$param]['tmp_name']);
178 // TRANS: Exception thrown when uploading a file as image that is not an image or is a corrupt file.
179 throw new UnsupportedMediaException(_('Not an image or corrupt file.'), '[deleted]');
182 return new ImageFile(null, $_FILES[$param]['tmp_name']);
186 * Compat interface for old code generating avatar thumbnails...
187 * Saves the scaled file directly into the avatar area.
189 * @param int $size target width & height -- must be square
190 * @param int $x (default 0) upper-left corner to crop from
191 * @param int $y (default 0) upper-left corner to crop from
192 * @param int $w (default full) width of image area to crop
193 * @param int $h (default full) height of image area to crop
194 * @return string filename
196 function resize($size, $x = 0, $y = 0, $w = null, $h = null)
198 $targetType = $this->preferredType();
199 $outname = Avatar::filename($this->id,
200 image_type_to_extension($targetType),
203 $outpath = Avatar::path($outname);
204 $this->resizeTo($outpath, array('width'=>$size, 'height'=>$size,
211 * Copy the image file to the given destination.
213 * This function may modify the resulting file. Please use the
214 * returned ImageFile object to read metadata (width, height etc.)
216 * @param string $outpath
217 * @return ImageFile the image stored at target path
219 function copyTo($outpath)
221 return new ImageFile(null, $this->resizeTo($outpath));
225 * Create and save a thumbnail image.
227 * @param string $outpath
228 * @param array $box width, height, boundary box (x,y,w,h) defaults to full image
229 * @return string full local filesystem filename
231 function resizeTo($outpath, array $box=array())
233 $box['width'] = isset($box['width']) ? intval($box['width']) : $this->width;
234 $box['height'] = isset($box['height']) ? intval($box['height']) : $this->height;
235 $box['x'] = isset($box['x']) ? intval($box['x']) : 0;
236 $box['y'] = isset($box['y']) ? intval($box['y']) : 0;
237 $box['w'] = isset($box['w']) ? intval($box['w']) : $this->width;
238 $box['h'] = isset($box['h']) ? intval($box['h']) : $this->height;
240 if (!file_exists($this->filepath)) {
241 // TRANS: Exception thrown during resize when image has been registered as present, but is no longer there.
242 throw new Exception(_('Lost our file.'));
245 // Don't rotate/crop/scale if it isn't necessary
246 if ($box['width'] === $this->width
247 && $box['height'] === $this->height
250 && $box['w'] === $this->width
251 && $box['h'] === $this->height
252 && $this->type == $this->preferredType()) {
253 if ($this->rotate == 0) {
254 // No rotational difference, just copy it as-is
255 @copy($this->filepath, $outpath);
258 @chmod($outpath, common_config('attachments', 'chmod'));
260 } elseif (abs($this->rotate) == 90) {
261 // Box is rotated 90 degrees in either direction,
262 // so we have to redefine x to y and vice versa.
263 $tmp = $box['width'];
264 $box['width'] = $box['height'];
265 $box['height'] = $tmp;
267 $box['x'] = $box['y'];
270 $box['w'] = $box['h'];
276 if (Event::handle('StartResizeImageFile', array($this, $outpath, $box))) {
277 $this->resizeToFile($outpath, $box);
280 if (!file_exists($outpath)) {
281 throw new UseFileAsThumbnailException($this->id);
287 protected function resizeToFile($outpath, array $box)
289 switch ($this->type) {
291 $image_src = imagecreatefromgif($this->filepath);
294 $image_src = imagecreatefromjpeg($this->filepath);
297 $image_src = imagecreatefrompng($this->filepath);
300 $image_src = imagecreatefrombmp($this->filepath);
303 $image_src = imagecreatefromwbmp($this->filepath);
306 $image_src = imagecreatefromxbm($this->filepath);
309 // TRANS: Exception thrown when trying to resize an unknown file type.
310 throw new Exception(_('Unknown file type'));
313 if ($this->rotate != 0) {
314 $image_src = imagerotate($image_src, $this->rotate, 0);
317 $image_dest = imagecreatetruecolor($box['width'], $box['height']);
319 if ($this->type == IMAGETYPE_GIF || $this->type == IMAGETYPE_PNG || $this->type == IMAGETYPE_BMP) {
321 $transparent_idx = imagecolortransparent($image_src);
323 if ($transparent_idx >= 0) {
325 $transparent_color = imagecolorsforindex($image_src, $transparent_idx);
326 $transparent_idx = imagecolorallocate($image_dest, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);
327 imagefill($image_dest, 0, 0, $transparent_idx);
328 imagecolortransparent($image_dest, $transparent_idx);
330 } elseif ($this->type == IMAGETYPE_PNG) {
332 imagealphablending($image_dest, false);
333 $transparent = imagecolorallocatealpha($image_dest, 0, 0, 0, 127);
334 imagefill($image_dest, 0, 0, $transparent);
335 imagesavealpha($image_dest, true);
340 imagecopyresampled($image_dest, $image_src, 0, 0, $box['x'], $box['y'], $box['width'], $box['height'], $box['w'], $box['h']);
342 switch ($this->preferredType()) {
344 imagegif($image_dest, $outpath);
347 imagejpeg($image_dest, $outpath, common_config('image', 'jpegquality'));
350 imagepng($image_dest, $outpath);
353 // TRANS: Exception thrown when trying resize an unknown file type.
354 throw new Exception(_('Unknown file type'));
357 // Always chmod 0644 (default) to have other processes (e.g. queue daemon read it)
358 @chmod($outpath, common_config('attachments', 'chmod'));
360 imagedestroy($image_src);
361 imagedestroy($image_dest);
366 * Several obscure file types should be normalized to PNG on resize.
368 * @fixme consider flattening anything not GIF or JPEG to PNG
371 function preferredType()
373 if($this->type == IMAGETYPE_BMP) {
374 //we don't want to save BMP... it's an inefficient, rare, antiquated format
376 return IMAGETYPE_PNG;
377 } else if($this->type == IMAGETYPE_WBMP) {
378 //we don't want to save WBMP... it's a rare format that we can't guarantee clients will support
380 return IMAGETYPE_PNG;
381 } else if($this->type == IMAGETYPE_XBM) {
382 //we don't want to save XBM... it's a rare format that we can't guarantee clients will support
384 return IMAGETYPE_PNG;
391 @unlink($this->filepath);
394 static function maxFileSize()
396 $value = ImageFile::maxFileSizeInt();
398 if ($value > 1024 * 1024) {
399 $value = $value/(1024*1024);
400 // TRANS: Number of megabytes. %d is the number.
401 return sprintf(_m('%dMB','%dMB',$value),$value);
402 } else if ($value > 1024) {
403 $value = $value/1024;
404 // TRANS: Number of kilobytes. %d is the number.
405 return sprintf(_m('%dkB','%dkB',$value),$value);
407 // TRANS: Number of bytes. %d is the number.
408 return sprintf(_m('%dB','%dB',$value),$value);
412 static function maxFileSizeInt()
414 return min(ImageFile::strToInt(ini_get('post_max_size')),
415 ImageFile::strToInt(ini_get('upload_max_filesize')),
416 ImageFile::strToInt(ini_get('memory_limit')));
419 static function strToInt($str)
421 $unit = substr($str, -1);
422 $num = substr($str, 0, -1);
424 switch(strtoupper($unit)){
436 public function scaleToFit($maxWidth=null, $maxHeight=null, $crop=null)
438 return self::getScalingValues($this->width, $this->height,
439 $maxWidth, $maxHeight, $crop, $this->rotate);
443 * Gets scaling values for images of various types. Cropping can be enabled.
445 * Values will scale _up_ to fit max values if cropping is enabled!
446 * With cropping disabled, the max value of each axis will be respected.
448 * @param $width int Original width
449 * @param $height int Original height
450 * @param $maxW int Resulting max width
451 * @param $maxH int Resulting max height
452 * @param $crop int Crop to the size (not preserving aspect ratio)
454 public static function getScalingValues($width, $height,
455 $maxW=null, $maxH=null,
456 $crop=null, $rotate=0)
458 $maxW = $maxW ?: common_config('thumbnail', 'width');
459 $maxH = $maxH ?: common_config('thumbnail', 'height');
461 if ($maxW < 1 || ($maxH !== null && $maxH < 1)) {
462 throw new ServerException('Bad parameters for ImageFile::getScalingValues');
463 } elseif ($maxH === null) {
464 // if maxH is null, we set maxH to equal maxW and enable crop
469 // Because GD doesn't understand EXIF orientation etc.
470 if (abs($rotate) == 90) {
476 // Cropping data (for original image size). Default values, 0 and null,
477 // imply no cropping and with preserved aspect ratio (per axis).
480 $cw = null; // crop area width
481 $ch = null; // crop area height
484 $s_ar = $width / $height;
485 $t_ar = $maxW / $maxH;
490 // Source aspect ratio differs from target, recalculate crop points!
492 $cx = floor($width / 2 - $height * $t_ar / 2);
493 $cw = ceil($height * $t_ar);
494 } elseif ($s_ar < $t_ar) {
495 $cy = floor($height / 2 - $width / $t_ar / 2);
496 $ch = ceil($width / $t_ar);
500 $rh = ceil($height * $rw / $width);
502 // Scaling caused too large height, decrease to max accepted value
505 $rw = ceil($width * $rh / $height);
508 return array(intval($rw), intval($rh),
509 intval($cx), intval($cy),
510 is_null($cw) ? $width : intval($cw),
511 is_null($ch) ? $height : intval($ch));
515 * Animated GIF test, courtesy of frank at huddler dot com et al:
516 * http://php.net/manual/en/function.imagecreatefromgif.php#104473
517 * Modified so avoid landing inside of a header (and thus not matching our regexp).
519 protected function isAnimatedGif()
521 if (!($fh = @fopen($this->filepath, 'rb'))) {
526 //an animated gif contains multiple "frames", with each frame having a
528 // * a static 4-byte sequence (\x00\x21\xF9\x04)
529 // * 4 variable bytes
530 // * a static 2-byte sequence (\x00\x2C)
531 // In total the header is maximum 10 bytes.
533 // We read through the file til we reach the end of the file, or we've found
534 // at least 2 frame headers
535 while(!feof($fh) && $count < 2) {
536 $chunk = fread($fh, 1024 * 100); //read 100kb at a time
537 $count += preg_match_all('#\x00\x21\xF9\x04.{4}\x00\x2C#s', $chunk, $matches);
538 // rewind in case we ended up in the middle of the header, but avoid
539 // infinite loop (i.e. don't rewind if we're already in the end).
540 if (!feof($fh) && ftell($fh) >= 9) {
541 fseek($fh, -9, SEEK_CUR);
550 //PHP doesn't (as of 2/24/2010) have an imagecreatefrombmp so conditionally define one
551 if(!function_exists('imagecreatefrombmp')){
552 //taken shamelessly from http://www.php.net/manual/en/function.imagecreatefromwbmp.php#86214
553 function imagecreatefrombmp($p_sFile)
555 // Load the image into a string
556 $file = fopen($p_sFile,"rb");
557 $read = fread($file,10);
558 while(!feof($file)&&($read<>""))
559 $read .= fread($file,1024);
561 $temp = unpack("H*",$read);
563 $header = substr($hex,0,108);
565 // Process the header
566 // Structure: http://www.fastgraph.com/help/bmp_header_format.html
567 if (substr($header,0,4)=="424d")
569 // Cut it in parts of 2 bytes
570 $header_parts = str_split($header,2);
572 // Get the width 4 bytes
573 $width = hexdec($header_parts[19].$header_parts[18]);
575 // Get the height 4 bytes
576 $height = hexdec($header_parts[23].$header_parts[22]);
578 // Unset the header params
579 unset($header_parts);
582 // Define starting X and Y
587 $image = imagecreatetruecolor($width,$height);
589 // Grab the body from the image
590 $body = substr($hex,108);
592 // Calculate if padding at the end-line is needed
593 // Divided by two to keep overview.
594 // 1 byte = 2 HEX-chars
595 $body_size = (strlen($body)/2);
596 $header_size = ($width*$height);
598 // Use end-line padding? Only when needed
599 $usePadding = ($body_size>($header_size*3)+4);
601 // Using a for-loop with index-calculation instaid of str_split to avoid large memory consumption
602 // Calculate the next DWORD-position in the body
603 for ($i=0;$i<$body_size;$i+=3)
605 // Calculate line-ending and padding
608 // If padding needed, ignore image-padding
609 // Shift i to the ending of the current 32-bit-block
613 // Reset horizontal position
616 // Raise the height-position (bottom-up)
619 // Reached the image-height? Break the for-loop
624 // Calculation of the RGB-pixel (defined as BGR in image-data)
625 // Define $i_pos as absolute position in the body
627 $r = hexdec($body[$i_pos+4].$body[$i_pos+5]);
628 $g = hexdec($body[$i_pos+2].$body[$i_pos+3]);
629 $b = hexdec($body[$i_pos].$body[$i_pos+1]);
631 // Calculate and draw the pixel
632 $color = imagecolorallocate($image,$r,$g,$b);
633 imagesetpixel($image,$x,$height-$y,$color);
635 // Raise the horizontal position
639 // Unset the body / free the memory
642 // Return image-object
645 } // if(!function_exists('imagecreatefrombmp'))