上传文件生成缩略图
昨天公司突然要一个上传文件带附件,还要一个带图片上传功能并且要生成缩略图效果,下面我就把我的代码贴出来吧.
首先来看看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");
}
}
就这么简单了,上页这种就是生成文件到目录了,还有一种就生成二进制在网页显示,当然你也可以保存到数据库了.然后读出.
补充:Php教程,Php安装