昨天公司突然要一個上傳文件帶附件,還要一個帶圖片上傳功能並且要生成縮略圖效果,下面我就把我的代碼貼出來吧.
首先來看看up.htm文件,代碼如下:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>無標題文檔</title>
</head>
<body>
<form action="s.php" method="post" enctype="multipart/form-data" name="form1" id="form1">
<input type="file" name="image" id="image" />
<label>
<input type="submit" name="button" id="button" value="提交" />
</label>
</form>
<label></label>
</body>
</html>
其實上頁就是一個簡單的htm 文件,把信息post給我們下面要講到的文件s.php
if($_FILES['image']['name']){
if($_FILES['image']['size']){
if($_FILES['image']['type'] == "image/pjpeg"){
$im = @imagecreatefromjpeg($_FILES['image']['tmp_name']);
$n_bmp.='.jpg';
}elseif($_FILES['image']['type'] == "image/x-png"){
$im = @imagecreatefrompng($_FILES['image']['tmp_name']);
$n_bmp.='.png';
}elseif($_FILES['image']['type'] == "image/gif"){
$im = @imagecreatefromgif($_FILES['image']['tmp_name']);
$n_bmp.='.gif';
}
}
ResizeImage($im,120,60,md5(date("Y-m-d H:i:s")));
ImageDestroy ($im);
$tag=1;
}
function ResizeImage($im,$maxwidth,$maxheight,$name){
$width = imagesx($im);
$height = imagesy($im);
if(($maxwidth && $width > $maxwidth) || ($maxheight && $height > $maxheight)){
if($maxwidth && $width > $maxwidth){
$widthratio = $maxwidth/$width;
$RESIZEWIDTH=true;
}
if($maxheight && $height > $maxheight){
$heightratio = $maxheight/$height;
$RESIZEHEIGHT=true;
}
if($RESIZEWIDTH && $RESIZEHEIGHT){
if($widthratio < $heightratio){
$ratio = $widthratio;
}else{
$ratio = $heightratio;
}
}elseif($RESIZEWIDTH){
$ratio = $widthratio;
}elseif($RESIZEHEIGHT){
$ratio = $heightratio;
}
$newwidth = $width * $ratio;
$newheight = $height * $ratio;
if(function_exists("imagecopyresampled")){
$newim = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
}else{
$newim = imagecreate($newwidth, $newheight);
imagecopyresized($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
}
ImageJpeg ($newim,$name . ".jpg");
ImageDestroy ($newim);
}else{
ImageJpeg ($im,$name . ".jpg");
}
}
就這麼簡單了,上頁這種就是生成文件到目錄了,還有一種就生成二進制在網頁顯示,當然你也可以保存到數據庫了.然後讀出.