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
56 var $mimetype = null; // The _ImageFile_ mimetype, _not_ the originating File object
58 protected $fileRecord = null;
60 function __construct($id, $filepath)
63 if (!empty($this->id)) {
64 $this->fileRecord = new File();
65 $this->fileRecord->id = $this->id;
66 if (!$this->fileRecord->find(true)) {
67 // If we have set an ID, we need that ID to exist!
68 throw new NoResultException($this->fileRecord);
72 // These do not have to be the same as fileRecord->filename for example,
73 // since we may have generated an image source file from something else!
74 $this->filepath = $filepath;
75 $this->filename = basename($filepath);
77 $info = @getimagesize($this->filepath);
80 ($info[2] == IMAGETYPE_GIF && function_exists('imagecreatefromgif')) ||
81 ($info[2] == IMAGETYPE_JPEG && function_exists('imagecreatefromjpeg')) ||
82 $info[2] == IMAGETYPE_BMP ||
83 ($info[2] == IMAGETYPE_WBMP && function_exists('imagecreatefromwbmp')) ||
84 ($info[2] == IMAGETYPE_XBM && function_exists('imagecreatefromxbm')) ||
85 ($info[2] == IMAGETYPE_PNG && function_exists('imagecreatefrompng')))) {
87 // TRANS: Exception thrown when trying to upload an unsupported image file format.
88 throw new UnsupportedMediaException(_('Unsupported image format.'), $this->filepath);
91 $this->width = $info[0];
92 $this->height = $info[1];
93 $this->type = $info[2];
94 $this->mimetype = $info['mime'];
96 if ($this->type == IMAGETYPE_JPEG && function_exists('exif_read_data')) {
97 // Orientation value to rotate thumbnails properly
98 $exif = @exif_read_data($this->filepath);
99 if (is_array($exif) && isset($exif['Orientation'])) {
100 switch ((int)$exif['Orientation']) {
101 case 1: // top is top
104 case 3: // top is bottom
107 case 6: // top is right
110 case 8: // top is left
114 // If we ever write this back, Orientation should be set to '1'
116 } elseif ($this->type === IMAGETYPE_GIF) {
117 $this->animated = $this->isAnimatedGif();
120 Event::handle('FillImageFileMetadata', array($this));
123 public static function fromFileObject(File $file)
126 $media = common_get_mime_media($file->mimetype);
127 if (Event::handle('CreateFileImageThumbnailSource', array($file, &$imgPath, $media))) {
128 if (empty($file->filename) && !file_exists($imgPath)) {
129 throw new UnsupportedMediaException(_('File without filename could not get a thumbnail source.'));
132 // First some mimetype specific exceptions
133 switch ($file->mimetype) {
134 case 'image/svg+xml':
135 throw new UseFileAsThumbnailException($file->id);
138 // And we'll only consider it an image if it has such a media type
141 $imgPath = $file->getPath();
144 throw new UnsupportedMediaException(_('Unsupported media format.'), $file->getPath());
148 if (!file_exists($imgPath)) {
149 throw new ServerException(sprintf('Image not available locally: %s', $imgPath));
153 $image = new ImageFile($file->getID(), $imgPath);
154 } catch (UnsupportedMediaException $e) {
155 // Avoid deleting the original
157 if ($imgPath !== $file->getPath()) {
160 } catch (FileNotFoundException $e) {
161 // File reported (via getPath) that the original file
162 // doesn't exist anyway, so it's safe to delete $imgPath
170 public function getPath()
172 if (!file_exists($this->filepath)) {
173 throw new FileNotFoundException($this->filepath);
176 return $this->filepath;
179 static function fromUpload($param='upload')
181 switch ($_FILES[$param]['error']) {
182 case UPLOAD_ERR_OK: // success, jump out
185 case UPLOAD_ERR_INI_SIZE:
186 case UPLOAD_ERR_FORM_SIZE:
187 // TRANS: Exception thrown when too large a file is uploaded.
188 // TRANS: %s is the maximum file size, for example "500b", "10kB" or "2MB".
189 throw new Exception(sprintf(_('That file is too big. The maximum file size is %s.'), ImageFile::maxFileSize()));
191 case UPLOAD_ERR_PARTIAL:
192 @unlink($_FILES[$param]['tmp_name']);
193 // TRANS: Exception thrown when uploading an image and that action could not be completed.
194 throw new Exception(_('Partial upload.'));
196 case UPLOAD_ERR_NO_FILE:
197 // No file; probably just a non-AJAX submission.
198 throw new ClientException(_('No file uploaded.'));
201 common_log(LOG_ERR, __METHOD__ . ": Unknown upload error " . $_FILES[$param]['error']);
202 // TRANS: Exception thrown when uploading an image fails for an unknown reason.
203 throw new Exception(_('System error uploading file.'));
206 $info = @getimagesize($_FILES[$param]['tmp_name']);
209 @unlink($_FILES[$param]['tmp_name']);
210 // TRANS: Exception thrown when uploading a file as image that is not an image or is a corrupt file.
211 throw new UnsupportedMediaException(_('Not an image or corrupt file.'), '[deleted]');
214 return new ImageFile(null, $_FILES[$param]['tmp_name']);
218 * Copy the image file to the given destination.
220 * This function may modify the resulting file. Please use the
221 * returned ImageFile object to read metadata (width, height etc.)
223 * @param string $outpath
224 * @return ImageFile the image stored at target path
226 function copyTo($outpath)
228 return new ImageFile(null, $this->resizeTo($outpath));
232 * Create and save a thumbnail image.
234 * @param string $outpath
235 * @param array $box width, height, boundary box (x,y,w,h) defaults to full image
236 * @return string full local filesystem filename
238 function resizeTo($outpath, array $box=array())
240 $box['width'] = isset($box['width']) ? intval($box['width']) : $this->width;
241 $box['height'] = isset($box['height']) ? intval($box['height']) : $this->height;
242 $box['x'] = isset($box['x']) ? intval($box['x']) : 0;
243 $box['y'] = isset($box['y']) ? intval($box['y']) : 0;
244 $box['w'] = isset($box['w']) ? intval($box['w']) : $this->width;
245 $box['h'] = isset($box['h']) ? intval($box['h']) : $this->height;
247 if (!file_exists($this->filepath)) {
248 // TRANS: Exception thrown during resize when image has been registered as present, but is no longer there.
249 throw new Exception(_('Lost our file.'));
252 // Don't rotate/crop/scale if it isn't necessary
253 if ($box['width'] === $this->width
254 && $box['height'] === $this->height
257 && $box['w'] === $this->width
258 && $box['h'] === $this->height
259 && $this->type == $this->preferredType()) {
260 if ($this->rotate == 0) {
261 // No rotational difference, just copy it as-is
262 @copy($this->filepath, $outpath);
264 } elseif (abs($this->rotate) == 90) {
265 // Box is rotated 90 degrees in either direction,
266 // so we have to redefine x to y and vice versa.
267 $tmp = $box['width'];
268 $box['width'] = $box['height'];
269 $box['height'] = $tmp;
271 $box['x'] = $box['y'];
274 $box['w'] = $box['h'];
280 if (Event::handle('StartResizeImageFile', array($this, $outpath, $box))) {
281 $this->resizeToFile($outpath, $box);
284 if (!file_exists($outpath)) {
285 throw new UseFileAsThumbnailException($this->id);
291 protected function resizeToFile($outpath, array $box)
293 switch ($this->type) {
295 $image_src = imagecreatefromgif($this->filepath);
298 $image_src = imagecreatefromjpeg($this->filepath);
301 $image_src = imagecreatefrompng($this->filepath);
304 $image_src = imagecreatefrombmp($this->filepath);
307 $image_src = imagecreatefromwbmp($this->filepath);
310 $image_src = imagecreatefromxbm($this->filepath);
313 // TRANS: Exception thrown when trying to resize an unknown file type.
314 throw new Exception(_('Unknown file type'));
317 if ($this->rotate != 0) {
318 $image_src = imagerotate($image_src, $this->rotate, 0);
321 $image_dest = imagecreatetruecolor($box['width'], $box['height']);
323 if ($this->type == IMAGETYPE_GIF || $this->type == IMAGETYPE_PNG || $this->type == IMAGETYPE_BMP) {
325 $transparent_idx = imagecolortransparent($image_src);
327 if ($transparent_idx >= 0) {
329 $transparent_color = imagecolorsforindex($image_src, $transparent_idx);
330 $transparent_idx = imagecolorallocate($image_dest, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);
331 imagefill($image_dest, 0, 0, $transparent_idx);
332 imagecolortransparent($image_dest, $transparent_idx);
334 } elseif ($this->type == IMAGETYPE_PNG) {
336 imagealphablending($image_dest, false);
337 $transparent = imagecolorallocatealpha($image_dest, 0, 0, 0, 127);
338 imagefill($image_dest, 0, 0, $transparent);
339 imagesavealpha($image_dest, true);
344 imagecopyresampled($image_dest, $image_src, 0, 0, $box['x'], $box['y'], $box['width'], $box['height'], $box['w'], $box['h']);
346 switch ($this->preferredType()) {
348 imagegif($image_dest, $outpath);
351 imagejpeg($image_dest, $outpath, common_config('image', 'jpegquality'));
354 imagepng($image_dest, $outpath);
357 // TRANS: Exception thrown when trying resize an unknown file type.
358 throw new Exception(_('Unknown file type'));
361 imagedestroy($image_src);
362 imagedestroy($image_dest);
367 * Several obscure file types should be normalized to PNG on resize.
369 * @fixme consider flattening anything not GIF or JPEG to PNG
372 function preferredType()
374 if($this->type == IMAGETYPE_BMP) {
375 //we don't want to save BMP... it's an inefficient, rare, antiquated format
377 return IMAGETYPE_PNG;
378 } else if($this->type == IMAGETYPE_WBMP) {
379 //we don't want to save WBMP... it's a rare format that we can't guarantee clients will support
381 return IMAGETYPE_PNG;
382 } else if($this->type == IMAGETYPE_XBM) {
383 //we don't want to save XBM... it's a rare format that we can't guarantee clients will support
385 return IMAGETYPE_PNG;
392 @unlink($this->filepath);
395 static function maxFileSize()
397 $value = ImageFile::maxFileSizeInt();
399 if ($value > 1024 * 1024) {
400 $value = $value/(1024*1024);
401 // TRANS: Number of megabytes. %d is the number.
402 return sprintf(_m('%dMB','%dMB',$value),$value);
403 } else if ($value > 1024) {
404 $value = $value/1024;
405 // TRANS: Number of kilobytes. %d is the number.
406 return sprintf(_m('%dkB','%dkB',$value),$value);
408 // TRANS: Number of bytes. %d is the number.
409 return sprintf(_m('%dB','%dB',$value),$value);
413 static function maxFileSizeInt()
415 return min(ImageFile::strToInt(ini_get('post_max_size')),
416 ImageFile::strToInt(ini_get('upload_max_filesize')),
417 ImageFile::strToInt(ini_get('memory_limit')));
420 static function strToInt($str)
422 $unit = substr($str, -1);
423 $num = substr($str, 0, -1);
425 switch(strtoupper($unit)){
437 public function scaleToFit($maxWidth=null, $maxHeight=null, $crop=null)
439 return self::getScalingValues($this->width, $this->height,
440 $maxWidth, $maxHeight, $crop, $this->rotate);
444 * Gets scaling values for images of various types. Cropping can be enabled.
446 * Values will scale _up_ to fit max values if cropping is enabled!
447 * With cropping disabled, the max value of each axis will be respected.
449 * @param $width int Original width
450 * @param $height int Original height
451 * @param $maxW int Resulting max width
452 * @param $maxH int Resulting max height
453 * @param $crop int Crop to the size (not preserving aspect ratio)
455 public static function getScalingValues($width, $height,
456 $maxW=null, $maxH=null,
457 $crop=null, $rotate=0)
459 $maxW = $maxW ?: common_config('thumbnail', 'width');
460 $maxH = $maxH ?: common_config('thumbnail', 'height');
462 if ($maxW < 1 || ($maxH !== null && $maxH < 1)) {
463 throw new ServerException('Bad parameters for ImageFile::getScalingValues');
464 } elseif ($maxH === null) {
465 // if maxH is null, we set maxH to equal maxW and enable crop
470 // Because GD doesn't understand EXIF orientation etc.
471 if (abs($rotate) == 90) {
477 // Cropping data (for original image size). Default values, 0 and null,
478 // imply no cropping and with preserved aspect ratio (per axis).
481 $cw = null; // crop area width
482 $ch = null; // crop area height
485 $s_ar = $width / $height;
486 $t_ar = $maxW / $maxH;
491 // Source aspect ratio differs from target, recalculate crop points!
493 $cx = floor($width / 2 - $height * $t_ar / 2);
494 $cw = ceil($height * $t_ar);
495 } elseif ($s_ar < $t_ar) {
496 $cy = floor($height / 2 - $width / $t_ar / 2);
497 $ch = ceil($width / $t_ar);
501 $rh = ceil($height * $rw / $width);
503 // Scaling caused too large height, decrease to max accepted value
506 $rw = ceil($width * $rh / $height);
509 return array(intval($rw), intval($rh),
510 intval($cx), intval($cy),
511 is_null($cw) ? $width : intval($cw),
512 is_null($ch) ? $height : intval($ch));
516 * Animated GIF test, courtesy of frank at huddler dot com et al:
517 * http://php.net/manual/en/function.imagecreatefromgif.php#104473
518 * Modified so avoid landing inside of a header (and thus not matching our regexp).
520 protected function isAnimatedGif()
522 if (!($fh = @fopen($this->filepath, 'rb'))) {
527 //an animated gif contains multiple "frames", with each frame having a
529 // * a static 4-byte sequence (\x00\x21\xF9\x04)
530 // * 4 variable bytes
531 // * a static 2-byte sequence (\x00\x2C)
532 // In total the header is maximum 10 bytes.
534 // We read through the file til we reach the end of the file, or we've found
535 // at least 2 frame headers
536 while(!feof($fh) && $count < 2) {
537 $chunk = fread($fh, 1024 * 100); //read 100kb at a time
538 $count += preg_match_all('#\x00\x21\xF9\x04.{4}\x00\x2C#s', $chunk, $matches);
539 // rewind in case we ended up in the middle of the header, but avoid
540 // infinite loop (i.e. don't rewind if we're already in the end).
541 if (!feof($fh) && ftell($fh) >= 9) {
542 fseek($fh, -9, SEEK_CUR);
550 public function getFileThumbnail($width, $height, $crop, $upscale=false)
552 if (!$this->fileRecord instanceof File) {
553 throw new ServerException('No File object attached to this ImageFile object.');
556 if ($width === null) {
557 $width = common_config('thumbnail', 'width');
558 $height = common_config('thumbnail', 'height');
559 $crop = common_config('thumbnail', 'crop');
563 if ($width > $this->width) {
564 $width = $this->width;
566 if (!is_null($height) && $height > $this->height) {
567 $height = $this->height;
571 if ($height === null) {
576 // Get proper aspect ratio width and height before lookup
577 // We have to do it through an ImageFile object because of orientation etc.
578 // Only other solution would've been to rotate + rewrite uploaded files
579 // which we don't want to do because we like original, untouched data!
580 list($width, $height, $x, $y, $w, $h) = $this->scaleToFit($width, $height, $crop);
582 $thumb = File_thumbnail::pkeyGet(array(
583 'file_id'=> $this->fileRecord->id,
587 if ($thumb instanceof File_thumbnail) {
591 $filename = $this->fileRecord->filehash ?: $this->filename; // Remote files don't have $this->filehash
592 $extension = File::guessMimeExtension($this->mimetype);
593 $outname = "thumb-{$this->fileRecord->id}-{$width}x{$height}-{$filename}." . $extension;
594 $outpath = File_thumbnail::path($outname);
596 // The boundary box for our resizing
597 $box = array('width'=>$width, 'height'=>$height,
601 // Doublecheck that parameters are sane and integers.
602 if ($box['width'] < 1 || $box['width'] > common_config('thumbnail', 'maxsize')
603 || $box['height'] < 1 || $box['height'] > common_config('thumbnail', 'maxsize')
604 || $box['w'] < 1 || $box['x'] >= $this->width
605 || $box['h'] < 1 || $box['y'] >= $this->height) {
606 // Fail on bad width parameter. If this occurs, it's due to algorithm in ImageFile->scaleToFit
607 common_debug("Boundary box parameters for resize of {$this->filepath} : ".var_export($box,true));
608 throw new ServerException('Bad thumbnail size parameters.');
611 common_debug(sprintf('Generating a thumbnail of File id==%u of size %ux%u', $this->fileRecord->id, $width, $height));
613 // Perform resize and store into file
614 $this->resizeTo($outpath, $box);
617 // Avoid deleting the original
618 if (!in_array($this->getPath(), [File::path($this->filename), File_thumbnail::path($this->filename)])) {
621 } catch (FileNotFoundException $e) {
622 // $this->getPath() says the file doesn't exist anyway, so no point in trying to delete it!
625 return File_thumbnail::saveThumbnail($this->fileRecord->getID(),
626 null, // no url since we generated it ourselves and can dynamically generate the url
632 //PHP doesn't (as of 2/24/2010) have an imagecreatefrombmp so conditionally define one
633 if(!function_exists('imagecreatefrombmp')){
634 //taken shamelessly from http://www.php.net/manual/en/function.imagecreatefromwbmp.php#86214
635 function imagecreatefrombmp($p_sFile)
637 // Load the image into a string
638 $file = fopen($p_sFile,"rb");
639 $read = fread($file,10);
640 while(!feof($file)&&($read<>""))
641 $read .= fread($file,1024);
643 $temp = unpack("H*",$read);
645 $header = substr($hex,0,108);
647 // Process the header
648 // Structure: http://www.fastgraph.com/help/bmp_header_format.html
649 if (substr($header,0,4)=="424d")
651 // Cut it in parts of 2 bytes
652 $header_parts = str_split($header,2);
654 // Get the width 4 bytes
655 $width = hexdec($header_parts[19].$header_parts[18]);
657 // Get the height 4 bytes
658 $height = hexdec($header_parts[23].$header_parts[22]);
660 // Unset the header params
661 unset($header_parts);
664 // Define starting X and Y
669 $image = imagecreatetruecolor($width,$height);
671 // Grab the body from the image
672 $body = substr($hex,108);
674 // Calculate if padding at the end-line is needed
675 // Divided by two to keep overview.
676 // 1 byte = 2 HEX-chars
677 $body_size = (strlen($body)/2);
678 $header_size = ($width*$height);
680 // Use end-line padding? Only when needed
681 $usePadding = ($body_size>($header_size*3)+4);
683 // Using a for-loop with index-calculation instaid of str_split to avoid large memory consumption
684 // Calculate the next DWORD-position in the body
685 for ($i=0;$i<$body_size;$i+=3)
687 // Calculate line-ending and padding
690 // If padding needed, ignore image-padding
691 // Shift i to the ending of the current 32-bit-block
695 // Reset horizontal position
698 // Raise the height-position (bottom-up)
701 // Reached the image-height? Break the for-loop
706 // Calculation of the RGB-pixel (defined as BGR in image-data)
707 // Define $i_pos as absolute position in the body
709 $r = hexdec($body[$i_pos+4].$body[$i_pos+5]);
710 $g = hexdec($body[$i_pos+2].$body[$i_pos+3]);
711 $b = hexdec($body[$i_pos].$body[$i_pos+1]);
713 // Calculate and draw the pixel
714 $color = imagecolorallocate($image,$r,$g,$b);
715 imagesetpixel($image,$x,$height-$y,$color);
717 // Raise the horizontal position
721 // Unset the body / free the memory
724 // Return image-object
727 } // if(!function_exists('imagecreatefrombmp'))