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('STATUSNET') && !defined('LACONICA')) {
36 * A wrapper on uploaded files
38 * Makes it slightly easier to accept an image file from upload.
42 * @author Evan Prodromou <evan@status.net>
43 * @author Zach Copley <zach@status.net>
44 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
45 * @link http://status.net/
57 function __construct($id=null, $filepath=null, $type=null, $width=null, $height=null)
60 $this->filepath = $filepath;
62 $info = @getimagesize($this->filepath);
65 ($info[2] == IMAGETYPE_GIF && function_exists('imagecreatefromgif')) ||
66 ($info[2] == IMAGETYPE_JPEG && function_exists('imagecreatefromjpeg')) ||
67 $info[2] == IMAGETYPE_BMP ||
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 throw new Exception(_('Unsupported image file format.'));
76 $this->type = ($info) ? $info[2]:$type;
77 $this->width = ($info) ? $info[0]:$width;
78 $this->height = ($info) ? $info[1]:$height;
81 static function fromUpload($param='upload')
83 switch ($_FILES[$param]['error']) {
84 case UPLOAD_ERR_OK: // success, jump out
86 case UPLOAD_ERR_INI_SIZE:
87 case UPLOAD_ERR_FORM_SIZE:
88 // TRANS: Exception thrown when too large a file is uploaded.
89 // TRANS: %s is the maximum file size, for example "500b", "10kB" or "2MB".
90 throw new Exception(sprintf(_('That file is too big. The maximum file size is %s.'),
91 ImageFile::maxFileSize()));
93 case UPLOAD_ERR_PARTIAL:
94 @unlink($_FILES[$param]['tmp_name']);
95 throw new Exception(_('Partial upload.'));
97 case UPLOAD_ERR_NO_FILE:
98 // No file; probably just a non-AJAX submission.
101 common_log(LOG_ERR, __METHOD__ . ": Unknown upload error " .
102 $_FILES[$param]['error']);
103 throw new Exception(_('System error uploading file.'));
107 $info = @getimagesize($_FILES[$param]['tmp_name']);
110 @unlink($_FILES[$param]['tmp_name']);
111 throw new Exception(_('Not an image or corrupt file.'));
115 return new ImageFile(null, $_FILES[$param]['tmp_name']);
119 * Compat interface for old code generating avatar thumbnails...
120 * Saves the scaled file directly into the avatar area.
122 * @param int $size target width & height -- must be square
123 * @param int $x (default 0) upper-left corner to crop from
124 * @param int $y (default 0) upper-left corner to crop from
125 * @param int $w (default full) width of image area to crop
126 * @param int $h (default full) height of image area to crop
127 * @return string filename
129 function resize($size, $x = 0, $y = 0, $w = null, $h = null)
131 $targetType = $this->preferredType($this->type);
132 $outname = Avatar::filename($this->id,
133 image_type_to_extension($targetType),
136 $outpath = Avatar::path($outname);
137 $this->resizeTo($outpath, $size, $size, $x, $y, $w, $h);
142 * Create and save a thumbnail image.
144 * @param string $outpath
145 * @param int $width target width
146 * @param int $height target height
147 * @param int $x (default 0) upper-left corner to crop from
148 * @param int $y (default 0) upper-left corner to crop from
149 * @param int $w (default full) width of image area to crop
150 * @param int $h (default full) height of image area to crop
151 * @return string full local filesystem filename
153 function resizeTo($outpath, $width, $height, $x=0, $y=0, $w=null, $h=null)
155 $w = ($w === null) ? $this->width:$w;
156 $h = ($h === null) ? $this->height:$h;
157 $targetType = $this->preferredType($this->type);
159 if (!file_exists($this->filepath)) {
160 throw new Exception(_('Lost our file.'));
164 // Don't crop/scale if it isn't necessary
165 if ($width === $this->width
166 && $height === $this->height
169 && $w === $this->width
170 && $h === $this->height
171 && $this->type == $targetType) {
173 @copy($this->filepath, $outpath);
177 switch ($this->type) {
179 $image_src = imagecreatefromgif($this->filepath);
182 $image_src = imagecreatefromjpeg($this->filepath);
185 $image_src = imagecreatefrompng($this->filepath);
188 $image_src = imagecreatefrombmp($this->filepath);
191 $image_src = imagecreatefromwbmp($this->filepath);
194 $image_src = imagecreatefromxbm($this->filepath);
197 throw new Exception(_('Unknown file type'));
201 $image_dest = imagecreatetruecolor($width, $height);
203 if ($this->type == IMAGETYPE_GIF || $this->type == IMAGETYPE_PNG || $this->type == IMAGETYPE_BMP) {
205 $transparent_idx = imagecolortransparent($image_src);
207 if ($transparent_idx >= 0) {
209 $transparent_color = imagecolorsforindex($image_src, $transparent_idx);
210 $transparent_idx = imagecolorallocate($image_dest, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);
211 imagefill($image_dest, 0, 0, $transparent_idx);
212 imagecolortransparent($image_dest, $transparent_idx);
214 } elseif ($this->type == IMAGETYPE_PNG) {
216 imagealphablending($image_dest, false);
217 $transparent = imagecolorallocatealpha($image_dest, 0, 0, 0, 127);
218 imagefill($image_dest, 0, 0, $transparent);
219 imagesavealpha($image_dest, true);
224 imagecopyresampled($image_dest, $image_src, 0, 0, $x, $y, $width, $height, $w, $h);
226 switch ($targetType) {
228 imagegif($image_dest, $outpath);
231 imagejpeg($image_dest, $outpath, 100);
234 imagepng($image_dest, $outpath);
237 throw new Exception(_('Unknown file type'));
241 imagedestroy($image_src);
242 imagedestroy($image_dest);
248 * Several obscure file types should be normalized to PNG on resize.
253 function preferredType($type)
255 if($type == IMAGETYPE_BMP) {
256 //we don't want to save BMP... it's an inefficient, rare, antiquated format
258 return IMAGETYPE_PNG;
259 } else if($type == IMAGETYPE_WBMP) {
260 //we don't want to save WBMP... it's a rare format that we can't guarantee clients will support
262 return IMAGETYPE_PNG;
263 } else if($type == IMAGETYPE_XBM) {
264 //we don't want to save XBM... it's a rare format that we can't guarantee clients will support
266 return IMAGETYPE_PNG;
273 @unlink($this->filename);
276 static function maxFileSize()
278 $value = ImageFile::maxFileSizeInt();
280 if ($value > 1024 * 1024) {
281 $value = $value/(1024*1024);
282 // TRANS: Number of megabytes. %d is the number.
283 return sprintf(_m('%dMB','%dMB',$value),$value);
284 } else if ($value > 1024) {
285 $value = $value/1024;
286 // TRANS: Number of kilobytes. %d is the number.
287 return sprintf(_m('%dkB','%dkB',$value),$value);
289 // TRANS: Number of bytes. %d is the number.
290 return sprintf(_m('%dB','%dB',$value),$value);
294 static function maxFileSizeInt()
296 return min(ImageFile::strToInt(ini_get('post_max_size')),
297 ImageFile::strToInt(ini_get('upload_max_filesize')),
298 ImageFile::strToInt(ini_get('memory_limit')));
301 static function strToInt($str)
303 $unit = substr($str, -1);
304 $num = substr($str, 0, -1);
306 switch(strtoupper($unit)){
319 //PHP doesn't (as of 2/24/2010) have an imagecreatefrombmp so conditionally define one
320 if(!function_exists('imagecreatefrombmp')){
321 //taken shamelessly from http://www.php.net/manual/en/function.imagecreatefromwbmp.php#86214
322 function imagecreatefrombmp($p_sFile)
324 // Load the image into a string
325 $file = fopen($p_sFile,"rb");
326 $read = fread($file,10);
327 while(!feof($file)&&($read<>""))
328 $read .= fread($file,1024);
330 $temp = unpack("H*",$read);
332 $header = substr($hex,0,108);
334 // Process the header
335 // Structure: http://www.fastgraph.com/help/bmp_header_format.html
336 if (substr($header,0,4)=="424d")
338 // Cut it in parts of 2 bytes
339 $header_parts = str_split($header,2);
341 // Get the width 4 bytes
342 $width = hexdec($header_parts[19].$header_parts[18]);
344 // Get the height 4 bytes
345 $height = hexdec($header_parts[23].$header_parts[22]);
347 // Unset the header params
348 unset($header_parts);
351 // Define starting X and Y
356 $image = imagecreatetruecolor($width,$height);
358 // Grab the body from the image
359 $body = substr($hex,108);
361 // Calculate if padding at the end-line is needed
362 // Divided by two to keep overview.
363 // 1 byte = 2 HEX-chars
364 $body_size = (strlen($body)/2);
365 $header_size = ($width*$height);
367 // Use end-line padding? Only when needed
368 $usePadding = ($body_size>($header_size*3)+4);
370 // Using a for-loop with index-calculation instaid of str_split to avoid large memory consumption
371 // Calculate the next DWORD-position in the body
372 for ($i=0;$i<$body_size;$i+=3)
374 // Calculate line-ending and padding
377 // If padding needed, ignore image-padding
378 // Shift i to the ending of the current 32-bit-block
382 // Reset horizontal position
385 // Raise the height-position (bottom-up)
388 // Reached the image-height? Break the for-loop
393 // Calculation of the RGB-pixel (defined as BGR in image-data)
394 // Define $i_pos as absolute position in the body
396 $r = hexdec($body[$i_pos+4].$body[$i_pos+5]);
397 $g = hexdec($body[$i_pos+2].$body[$i_pos+3]);
398 $b = hexdec($body[$i_pos].$body[$i_pos+1]);
400 // Calculate and draw the pixel
401 $color = imagecolorallocate($image,$r,$g,$b);
402 imagesetpixel($image,$x,$height-$y,$color);
404 // Raise the horizontal position
408 // Unset the body / free the memory
411 // Return image-object