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);
63 $this->type = ($info) ? $info[2]:$type;
64 $this->width = ($info) ? $info[0]:$width;
65 $this->height = ($info) ? $info[1]:$height;
68 static function fromUpload($param='upload')
70 switch ($_FILES[$param]['error']) {
71 case UPLOAD_ERR_OK: // success, jump out
73 case UPLOAD_ERR_INI_SIZE:
74 case UPLOAD_ERR_FORM_SIZE:
75 throw new Exception(sprintf(_('That file is too big. The maximum file size is %s.'),
76 ImageFile::maxFileSize()));
78 case UPLOAD_ERR_PARTIAL:
79 @unlink($_FILES[$param]['tmp_name']);
80 throw new Exception(_('Partial upload.'));
82 case UPLOAD_ERR_NO_FILE:
83 // No file; probably just a non-AJAX submission.
86 common_log(LOG_ERR, __METHOD__ . ": Unknown upload error " .
87 $_FILES[$param]['error']);
88 throw new Exception(_('System error uploading file.'));
92 $info = @getimagesize($_FILES[$param]['tmp_name']);
95 @unlink($_FILES[$param]['tmp_name']);
96 throw new Exception(_('Not an image or corrupt file.'));
100 if ($info[2] !== IMAGETYPE_GIF &&
101 $info[2] !== IMAGETYPE_JPEG &&
102 $info[2] !== IMAGETYPE_BMP &&
103 $info[2] !== IMAGETYPE_WBMP &&
104 $info[2] !== IMAGETYPE_XBM &&
105 $info[2] !== IMAGETYPE_XPM &&
106 $info[2] !== IMAGETYPE_PNG) {
108 @unlink($_FILES[$param]['tmp_name']);
109 throw new Exception(_('Unsupported image file format.'));
113 return new ImageFile(null, $_FILES[$param]['tmp_name']);
116 function resize($size, $x = 0, $y = 0, $w = null, $h = null)
118 $w = ($w === null) ? $this->width:$w;
119 $h = ($h === null) ? $this->height:$h;
121 if (!file_exists($this->filepath)) {
122 throw new Exception(_('Lost our file.'));
126 // Don't crop/scale if it isn't necessary
127 if ($size === $this->width
128 && $size === $this->height
131 && $w === $this->width
132 && $h === $this->height) {
134 $outname = Avatar::filename($this->id,
135 image_type_to_extension($this->type),
138 $outpath = Avatar::path($outname);
139 @copy($this->filepath, $outpath);
143 switch ($this->type) {
145 $image_src = imagecreatefromgif($this->filepath);
148 $image_src = imagecreatefromjpeg($this->filepath);
151 $image_src = imagecreatefrompng($this->filepath);
154 $image_src = imagecreatefrombmp($this->filepath);
157 $image_src = imagecreatefromwbmp($this->filepath);
160 $image_src = imagecreatefromxbm($this->filepath);
163 $image_src = imagecreatefromxpm($this->filepath);
166 throw new Exception(_('Unknown file type'));
170 $image_dest = imagecreatetruecolor($size, $size);
172 if ($this->type == IMAGETYPE_GIF || $this->type == IMAGETYPE_PNG || $this->type == IMAGETYPE_BMP) {
174 $transparent_idx = imagecolortransparent($image_src);
176 if ($transparent_idx >= 0) {
178 $transparent_color = imagecolorsforindex($image_src, $transparent_idx);
179 $transparent_idx = imagecolorallocate($image_dest, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);
180 imagefill($image_dest, 0, 0, $transparent_idx);
181 imagecolortransparent($image_dest, $transparent_idx);
183 } elseif ($this->type == IMAGETYPE_PNG) {
185 imagealphablending($image_dest, false);
186 $transparent = imagecolorallocatealpha($image_dest, 0, 0, 0, 127);
187 imagefill($image_dest, 0, 0, $transparent);
188 imagesavealpha($image_dest, true);
193 imagecopyresampled($image_dest, $image_src, 0, 0, $x, $y, $size, $size, $w, $h);
195 if($this->type == IMAGETYPE_BMP) {
196 //we don't want to save BMP... it's an inefficient, rare, antiquated format
198 $this->type = IMAGETYPE_PNG;
199 } else if($this->type == IMAGETYPE_WBMP) {
200 //we don't want to save WBMP... it's a rare format that we can't guarantee clients will support
202 $this->type = IMAGETYPE_PNG;
203 } else if($this->type == IMAGETYPE_XBM) {
204 //we don't want to save XBM... it's a rare format that we can't guarantee clients will support
206 $this->type = IMAGETYPE_PNG;
207 } else if($this->type == IMAGETYPE_XPM) {
208 //we don't want to save XPM... it's a rare format that we can't guarantee clients will support
210 $this->type = IMAGETYPE_PNG;
213 $outname = Avatar::filename($this->id,
214 image_type_to_extension($this->type),
218 $outpath = Avatar::path($outname);
220 switch ($this->type) {
222 imagegif($image_dest, $outpath);
225 imagejpeg($image_dest, $outpath, 100);
228 imagepng($image_dest, $outpath);
231 throw new Exception(_('Unknown file type'));
235 imagedestroy($image_src);
236 imagedestroy($image_dest);
243 @unlink($this->filename);
246 static function maxFileSize()
248 $value = ImageFile::maxFileSizeInt();
250 if ($value > 1024 * 1024) {
251 return ($value/(1024*1024)) . _('MB');
252 } else if ($value > 1024) {
253 return ($value/(1024)) . _('kB');
259 static function maxFileSizeInt()
261 return min(ImageFile::strToInt(ini_get('post_max_size')),
262 ImageFile::strToInt(ini_get('upload_max_filesize')),
263 ImageFile::strToInt(ini_get('memory_limit')));
266 static function strToInt($str)
268 $unit = substr($str, -1);
269 $num = substr($str, 0, -1);
271 switch(strtoupper($unit)){
284 //PHP doesn't (as of 2/24/2010) have an imagecreatefrombmp so conditionally define one
285 if(!function_exists('imagecreatefrombmp')){
286 //taken shamelessly from http://www.php.net/manual/en/function.imagecreatefromwbmp.php#86214
287 function imagecreatefrombmp($p_sFile)
289 // Load the image into a string
290 $file = fopen($p_sFile,"rb");
291 $read = fread($file,10);
292 while(!feof($file)&&($read<>""))
293 $read .= fread($file,1024);
295 $temp = unpack("H*",$read);
297 $header = substr($hex,0,108);
299 // Process the header
300 // Structure: http://www.fastgraph.com/help/bmp_header_format.html
301 if (substr($header,0,4)=="424d")
303 // Cut it in parts of 2 bytes
304 $header_parts = str_split($header,2);
306 // Get the width 4 bytes
307 $width = hexdec($header_parts[19].$header_parts[18]);
309 // Get the height 4 bytes
310 $height = hexdec($header_parts[23].$header_parts[22]);
312 // Unset the header params
313 unset($header_parts);
316 // Define starting X and Y
321 $image = imagecreatetruecolor($width,$height);
323 // Grab the body from the image
324 $body = substr($hex,108);
326 // Calculate if padding at the end-line is needed
327 // Divided by two to keep overview.
328 // 1 byte = 2 HEX-chars
329 $body_size = (strlen($body)/2);
330 $header_size = ($width*$height);
332 // Use end-line padding? Only when needed
333 $usePadding = ($body_size>($header_size*3)+4);
335 // Using a for-loop with index-calculation instaid of str_split to avoid large memory consumption
336 // Calculate the next DWORD-position in the body
337 for ($i=0;$i<$body_size;$i+=3)
339 // Calculate line-ending and padding
342 // If padding needed, ignore image-padding
343 // Shift i to the ending of the current 32-bit-block
347 // Reset horizontal position
350 // Raise the height-position (bottom-up)
353 // Reached the image-height? Break the for-loop
358 // Calculation of the RGB-pixel (defined as BGR in image-data)
359 // Define $i_pos as absolute position in the body
361 $r = hexdec($body[$i_pos+4].$body[$i_pos+5]);
362 $g = hexdec($body[$i_pos+2].$body[$i_pos+3]);
363 $b = hexdec($body[$i_pos].$body[$i_pos+1]);
365 // Calculate and draw the pixel
366 $color = imagecolorallocate($image,$r,$g,$b);
367 imagesetpixel($image,$x,$height-$y,$color);
369 // Raise the horizontal position
373 // Unset the body / free the memory
376 // Return image-object