<form name="form1" method="post" enctype="multipart/form-data" action="..."> <input name="file1" type="file"> </form>
並且將上傳檔案並縮圖的程式整理成兩個函式
function ImageResize($from_filename, $save_filename, $in_width=400, $in_height=300, $quality=100) { // 首先取得來源圖檔的資訊 $img_info = getimagesize($from_filename); $width = $img_info['0']; $height = $img_info['1']; $imgtype = $img_info['2']; $imgtag = $img_info['3']; $bits = $img_info['bits']; $channels = $img_info['channels']; $mime = $img_info['mime']; $sub_name = $t = ''; // 利用mime屬性來判斷要產生什麼格式的新image list($t, $sub_name) = split('/', $mime); // 取得縮在此範圍內的比例 $percent = getResizePercent($width, $height, $in_width, $in_height); $new_width = $width * $percent; $new_height = $height * $percent; // Resample $image_new = imagecreatetruecolor($new_width, $new_height); $image = null; if ($sub_name == "jpeg") { $image = imagecreatefromjpeg($from_filename); $sub_name = ".jpg"; } else if ($sub_name == "png") { $image = imagecreatefrompng($from_filename); $sub_name = ".png"; } else if ($sub_name == "gif") { $image = imagecreatefromgif($from_filename); $sub_name = ".gif"; } // 利用imagecopyresampled函式來縮圖 imagecopyresampled($image_new, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); // 產生圖檔到指定路徑 imagejpeg($image_new, $save_filename.$sub_name, $quality); } function getResizePercent($source_w, $source_h, $inside_w, $inside_h) { if ($source_w < $inside_w && $source_h < $inside_h) { return 1; // Percent = 1, 如果都比預計縮圖的小就不用縮 } $w_percent = $inside_w / $source_w; $h_percent = $inside_h / $source_h; return ($w_percent > $h_percent) ? $h_percent : $w_percent; }
接下來是使用函式的方法
$uploaddir = "images/"; $uploadfile = $uploaddir.basename($_FILES['file1']['name']); ImageResize($_FILES['file1']['tmp_name'], $uploadfile);上傳檔案時,上傳的檔案會先存放到伺服器上的一個暫存目錄,
$_FILES['file1']['tmp_name']會取得該暫存檔的絕對路徑,
而$_FILES['file1']['name']就是被選取上傳檔案的檔名。
這裡要註記一個重點:
只要上傳的檔案大小加上post本身的大小,超過 post_max_size 的限定,
就接收不到資料了(沒錯誤訊息,連一般post欄位的值也會都是空的!!)
沒有留言:
張貼留言