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/
55 function __construct($id=null, $filepath=null, $type=null, $width=null, $height=null)
58 $this->filepath = $filepath;
60 $info = @getimagesize($this->filepath);
63 ($info[2] == IMAGETYPE_GIF && function_exists('imagecreatefromgif')) ||
64 ($info[2] == IMAGETYPE_JPEG && function_exists('imagecreatefromjpeg')) ||
65 $info[2] == IMAGETYPE_BMP ||
66 ($info[2] == IMAGETYPE_WBMP && function_exists('imagecreatefromwbmp')) ||
67 ($info[2] == IMAGETYPE_XBM && function_exists('imagecreatefromxbm')) ||
68 ($info[2] == IMAGETYPE_PNG && function_exists('imagecreatefrompng')))) {
70 // TRANS: Exception thrown when trying to upload an unsupported image file format.
71 throw new UnsupportedMediaException(_('Unsupported image format.'), $this->filepath);
74 $this->type = ($info) ? $info[2]:$type;
75 $this->width = ($info) ? $info[0]:$width;
76 $this->height = ($info) ? $info[1]:$height;
79 public static function fromFileObject(File $file)
82 $media = common_get_mime_media($file->mimetype);
83 if (Event::handle('CreateFileImageThumbnailSource', array($file, &$imgPath, $media))) {
86 $imgPath = $file->getPath();
89 throw new UnsupportedMediaException(_('Unsupported media format.'), $file->getPath());
93 if (!file_exists($imgPath)) {
94 throw new ServerException(sprintf('Image not available locally: %s', $imgPath));
98 $image = new ImageFile($file->id, $imgPath);
99 } catch (UnsupportedMediaException $e) {
100 // Avoid deleting the original
101 if ($imgPath != $file->getPath()) {
109 public function getPath()
111 if (!file_exists($this->filepath)) {
112 throw new ServerException('No file in ImageFile filepath');
115 return $this->filepath;
118 static function fromUpload($param='upload')
120 switch ($_FILES[$param]['error']) {
121 case UPLOAD_ERR_OK: // success, jump out
124 case UPLOAD_ERR_INI_SIZE:
125 case UPLOAD_ERR_FORM_SIZE:
126 // TRANS: Exception thrown when too large a file is uploaded.
127 // TRANS: %s is the maximum file size, for example "500b", "10kB" or "2MB".
128 throw new Exception(sprintf(_('That file is too big. The maximum file size is %s.'), ImageFile::maxFileSize()));
130 case UPLOAD_ERR_PARTIAL:
131 @unlink($_FILES[$param]['tmp_name']);
132 // TRANS: Exception thrown when uploading an image and that action could not be completed.
133 throw new Exception(_('Partial upload.'));
135 case UPLOAD_ERR_NO_FILE:
136 // No file; probably just a non-AJAX submission.
138 common_log(LOG_ERR, __METHOD__ . ": Unknown upload error " . $_FILES[$param]['error']);
139 // TRANS: Exception thrown when uploading an image fails for an unknown reason.
140 throw new Exception(_('System error uploading file.'));
143 $info = @getimagesize($_FILES[$param]['tmp_name']);
146 @unlink($_FILES[$param]['tmp_name']);
147 // TRANS: Exception thrown when uploading a file as image that is not an image or is a corrupt file.
148 throw new UnsupportedMediaException(_('Not an image or corrupt file.'), '[deleted]');
151 return new ImageFile(null, $_FILES[$param]['tmp_name']);
155 * Compat interface for old code generating avatar thumbnails...
156 * Saves the scaled file directly into the avatar area.
158 * @param int $size target width & height -- must be square
159 * @param int $x (default 0) upper-left corner to crop from
160 * @param int $y (default 0) upper-left corner to crop from
161 * @param int $w (default full) width of image area to crop
162 * @param int $h (default full) height of image area to crop
163 * @return string filename
165 function resize($size, $x = 0, $y = 0, $w = null, $h = null)
167 $targetType = $this->preferredType();
168 $outname = Avatar::filename($this->id,
169 image_type_to_extension($targetType),
172 $outpath = Avatar::path($outname);
173 $this->resizeTo($outpath, $size, $size, $x, $y, $w, $h);
178 * Copy the image file to the given destination.
179 * For obscure formats, this will automatically convert to PNG;
180 * otherwise the original file will be copied as-is.
182 * @param string $outpath
183 * @return string filename
185 function copyTo($outpath)
187 return $this->resizeTo($outpath, $this->width, $this->height);
191 * Create and save a thumbnail image.
193 * @param string $outpath
194 * @param int $width target width
195 * @param int $height target height
196 * @param int $x (default 0) upper-left corner to crop from
197 * @param int $y (default 0) upper-left corner to crop from
198 * @param int $w (default full) width of image area to crop
199 * @param int $h (default full) height of image area to crop
200 * @return string full local filesystem filename
202 function resizeTo($outpath, $width, $height, $x=0, $y=0, $w=null, $h=null)
204 $w = ($w === null) ? $this->width:$w;
205 $h = ($h === null) ? $this->height:$h;
206 $targetType = $this->preferredType();
208 if (!file_exists($this->filepath)) {
209 // TRANS: Exception thrown during resize when image has been registered as present, but is no longer there.
210 throw new Exception(_('Lost our file.'));
213 // Don't crop/scale if it isn't necessary
214 if ($width === $this->width
215 && $height === $this->height
218 && $w === $this->width
219 && $h === $this->height
220 && $this->type == $targetType) {
222 @copy($this->filepath, $outpath);
226 switch ($this->type) {
228 $image_src = imagecreatefromgif($this->filepath);
231 $image_src = imagecreatefromjpeg($this->filepath);
234 $image_src = imagecreatefrompng($this->filepath);
237 $image_src = imagecreatefrombmp($this->filepath);
240 $image_src = imagecreatefromwbmp($this->filepath);
243 $image_src = imagecreatefromxbm($this->filepath);
246 // TRANS: Exception thrown when trying to resize an unknown file type.
247 throw new Exception(_('Unknown file type'));
250 $image_dest = imagecreatetruecolor($width, $height);
252 if ($this->type == IMAGETYPE_GIF || $this->type == IMAGETYPE_PNG || $this->type == IMAGETYPE_BMP) {
254 $transparent_idx = imagecolortransparent($image_src);
256 if ($transparent_idx >= 0) {
258 $transparent_color = imagecolorsforindex($image_src, $transparent_idx);
259 $transparent_idx = imagecolorallocate($image_dest, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);
260 imagefill($image_dest, 0, 0, $transparent_idx);
261 imagecolortransparent($image_dest, $transparent_idx);
263 } elseif ($this->type == IMAGETYPE_PNG) {
265 imagealphablending($image_dest, false);
266 $transparent = imagecolorallocatealpha($image_dest, 0, 0, 0, 127);
267 imagefill($image_dest, 0, 0, $transparent);
268 imagesavealpha($image_dest, true);
273 imagecopyresampled($image_dest, $image_src, 0, 0, $x, $y, $width, $height, $w, $h);
275 switch ($targetType) {
277 imagegif($image_dest, $outpath);
280 imagejpeg($image_dest, $outpath, common_config('image', 'jpegquality'));
283 imagepng($image_dest, $outpath);
286 // TRANS: Exception thrown when trying resize an unknown file type.
287 throw new Exception(_('Unknown file type'));
290 imagedestroy($image_src);
291 imagedestroy($image_dest);
297 * Several obscure file types should be normalized to PNG on resize.
299 * @fixme consider flattening anything not GIF or JPEG to PNG
302 function preferredType()
304 if($this->type == IMAGETYPE_BMP) {
305 //we don't want to save BMP... it's an inefficient, rare, antiquated format
307 return IMAGETYPE_PNG;
308 } else if($this->type == IMAGETYPE_WBMP) {
309 //we don't want to save WBMP... it's a rare format that we can't guarantee clients will support
311 return IMAGETYPE_PNG;
312 } else if($this->type == IMAGETYPE_XBM) {
313 //we don't want to save XBM... it's a rare format that we can't guarantee clients will support
315 return IMAGETYPE_PNG;
322 @unlink($this->filepath);
325 static function maxFileSize()
327 $value = ImageFile::maxFileSizeInt();
329 if ($value > 1024 * 1024) {
330 $value = $value/(1024*1024);
331 // TRANS: Number of megabytes. %d is the number.
332 return sprintf(_m('%dMB','%dMB',$value),$value);
333 } else if ($value > 1024) {
334 $value = $value/1024;
335 // TRANS: Number of kilobytes. %d is the number.
336 return sprintf(_m('%dkB','%dkB',$value),$value);
338 // TRANS: Number of bytes. %d is the number.
339 return sprintf(_m('%dB','%dB',$value),$value);
343 static function maxFileSizeInt()
345 return min(ImageFile::strToInt(ini_get('post_max_size')),
346 ImageFile::strToInt(ini_get('upload_max_filesize')),
347 ImageFile::strToInt(ini_get('memory_limit')));
350 static function strToInt($str)
352 $unit = substr($str, -1);
353 $num = substr($str, 0, -1);
355 switch(strtoupper($unit)){
367 public function scaleToFit($maxWidth=null, $maxHeight=null, $crop=null)
369 return self::getScalingValues($this->width, $this->height,
370 $maxWidth, $maxHeight, $crop);
374 * Gets scaling values for images of various types. Cropping can be enabled.
376 * Values will scale _up_ to fit max values if cropping is enabled!
377 * With cropping disabled, the max value of each axis will be respected.
379 * @param $width int Original width
380 * @param $height int Original height
381 * @param $maxW int Resulting max width
382 * @param $maxH int Resulting max height
383 * @param $crop int Crop to the size (not preserving aspect ratio)
385 public static function getScalingValues($width, $height,
386 $maxW=null, $maxH=null,
389 $maxW = $maxW ?: common_config('thumbnail', 'width');
390 $maxH = $maxH ?: common_config('thumbnail', 'height');
392 if ($maxW < 1 || ($maxH !== null && $maxH < 1)) {
393 throw new ServerException('Bad parameters for ImageFile::getScalingValues');
394 } elseif ($maxH === null) {
395 // if maxH is null, we set maxH to equal maxW and enable crop
400 // Cropping data (for original image size). Default values, 0 and null,
401 // imply no cropping and with preserved aspect ratio (per axis).
404 $cw = null; // crop area width
405 $ch = null; // crop area height
408 $s_ar = $width / $height;
409 $t_ar = $maxW / $maxH;
414 // Source aspect ratio differs from target, recalculate crop points!
416 $cx = floor($width / 2 - $height * $t_ar / 2);
417 $cw = ceil($height * $t_ar);
418 } elseif ($s_ar < $t_ar) {
419 $cy = floor($height / 2 - $width / $t_ar / 2);
420 $ch = ceil($width / $t_ar);
424 $rh = ceil($height * $rw / $width);
426 // Scaling caused too large height, decrease to max accepted value
429 $rw = ceil($width * $rh / $height);
432 return array(intval($rw), intval($rh),
433 intval($cx), intval($cy),
434 is_null($cw) ? $width : intval($cw),
435 is_null($ch) ? $height : intval($ch));
439 //PHP doesn't (as of 2/24/2010) have an imagecreatefrombmp so conditionally define one
440 if(!function_exists('imagecreatefrombmp')){
441 //taken shamelessly from http://www.php.net/manual/en/function.imagecreatefromwbmp.php#86214
442 function imagecreatefrombmp($p_sFile)
444 // Load the image into a string
445 $file = fopen($p_sFile,"rb");
446 $read = fread($file,10);
447 while(!feof($file)&&($read<>""))
448 $read .= fread($file,1024);
450 $temp = unpack("H*",$read);
452 $header = substr($hex,0,108);
454 // Process the header
455 // Structure: http://www.fastgraph.com/help/bmp_header_format.html
456 if (substr($header,0,4)=="424d")
458 // Cut it in parts of 2 bytes
459 $header_parts = str_split($header,2);
461 // Get the width 4 bytes
462 $width = hexdec($header_parts[19].$header_parts[18]);
464 // Get the height 4 bytes
465 $height = hexdec($header_parts[23].$header_parts[22]);
467 // Unset the header params
468 unset($header_parts);
471 // Define starting X and Y
476 $image = imagecreatetruecolor($width,$height);
478 // Grab the body from the image
479 $body = substr($hex,108);
481 // Calculate if padding at the end-line is needed
482 // Divided by two to keep overview.
483 // 1 byte = 2 HEX-chars
484 $body_size = (strlen($body)/2);
485 $header_size = ($width*$height);
487 // Use end-line padding? Only when needed
488 $usePadding = ($body_size>($header_size*3)+4);
490 // Using a for-loop with index-calculation instaid of str_split to avoid large memory consumption
491 // Calculate the next DWORD-position in the body
492 for ($i=0;$i<$body_size;$i+=3)
494 // Calculate line-ending and padding
497 // If padding needed, ignore image-padding
498 // Shift i to the ending of the current 32-bit-block
502 // Reset horizontal position
505 // Raise the height-position (bottom-up)
508 // Reached the image-height? Break the for-loop
513 // Calculation of the RGB-pixel (defined as BGR in image-data)
514 // Define $i_pos as absolute position in the body
516 $r = hexdec($body[$i_pos+4].$body[$i_pos+5]);
517 $g = hexdec($body[$i_pos+2].$body[$i_pos+3]);
518 $b = hexdec($body[$i_pos].$body[$i_pos+1]);
520 // Calculate and draw the pixel
521 $color = imagecolorallocate($image,$r,$g,$b);
522 imagesetpixel($image,$x,$height-$y,$color);
524 // Raise the horizontal position
528 // Unset the body / free the memory
531 // Return image-object
534 } // if(!function_exists('imagecreatefrombmp'))