ASP.NET中FileUpload控件上传图片时等比例缩放,然后保存到数据库
2011-09-0209:04:13| 分类: ASP.NET|字号 订阅
前台代码:
<%@ Page Language="C#" AutoEventWireup="true"CodeFile="attach.aspx.cs" Inherits="ywbl_attach" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>上传图片</title>
<!-- 注意下面一行不能少-->
<base target="_self" />
<link href="../images/style_all.css"rel="stylesheet" type="text/css" />
<script type="text/javascript">
function CheckWorkFile()
{
// varobj=document.getElementById("FileUpload1");
// if(obj.value=="")
// {
// alert('请先选择要上传的图片!');
// returnfalse;
// }
//
// var PicOK = 0;
// varstrExtension=obj.value.substring(obj.value.lastIndexOf("."),obj.value.length)
// var pic_format =<%=ConfigurationManager.AppSettings["pic_format"] %>;
// var Extensions =pic_format.split("|");
//
// for (int i = 0; i <Extensions.length; i++)
// {
// if(strExtension == Extensions[i])
// {
// PicOK = 1;
// break;
// }
// }
//
// if (PicOK==0)
// {
// alert("上传图片格式不对,只允许上传"+ pic_format + "格式的图片!");
// returnfalse;
// }
return true;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<br />
<tablewidth="100%" border="0" cellpadding="3"cellspacing="1">
<tr>
<td align="center">
<asp:FileUpload ID="FileUpload1" runat="server"CssClass="input" />
<asp:Button ID="btnFilt" runat="server" Text="上传"CssClass="input" OnClientClick="return CheckWorkFile();"OnClick="btnFilt_Click" />
</td>
</tr>
</table>
<br />
<tablewidth="100%" border="0" cellpadding="3"cellspacing="1">
<tr>
<td align="center">
<input id="btnClose" type="button" value=" 关闭 "class="button1" οnclick="window.close();return false;"/>
</td>
</tr>
</table>
<!--弹出的条件对话框-->
<asp:Literal ID="lblAlert" runat="server" />
</div>
</form>
</body>
</html>
后台代码:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
//引人命名空间
using System.Text;
using Com.Netmarch.Model;
using Com.Netmarch.BLL;
using Com.Netmarch.Utility;
using System.IO;
public partial class ywbl_attach : System.Web.UI.Page
{
private Com.Netmarch.BLL.WebPicture webpicture = newWebPicture();
private Com.Netmarch.BLL.SDKYWebPicture sdkywebpicture = newSDKYWebPicture();
protected void Page_Load(object sender,EventArgs e)
{
if (!this.IsPostBack)
{
//价格鉴证标的
ViewState["JGJZBD_ID"] = Request.QueryString["JGJZBD_ID"]== null ? "0" : Request.QueryString["JGJZBD_ID"];
ViewState["type"] = Request.QueryString["Type"] == null ?"0" :Request.QueryString["Type"];
}
}
//计算文件大小
private string GetFileSize(int FileSize)
{
int Level = 0;
double DobSize =Convert.ToDouble(FileSize);
while (DobSize / 1024 > 1)
{
Level++;
DobSize =DobSize / 1024;
}
string FSValue = DobSize.ToString();
if (FSValue.IndexOf(".") +3 <= FSValue.Length)
{
FSValue =FSValue.Substring(0, FSValue.IndexOf(".") + 3);
}
string retValue = "";
switch (Level)
{
case 0:retValue = FSValue + "Bytes"; break;
case 1:retValue = FSValue + "KB"; break;
case 2:retValue = FSValue + "MB"; break;
default:retValue = "未知大小";break;
}
return retValue;
}
//根据路径将文件转换为2进制数组
public byte[] Returnbyte(string strpath)
{
//以二进制方式读文件
FileStream fsMyfile = newFileStream(strpath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
//创建一个二进制数据流读入器,和打开的文件关联
BinaryReader brMyfile = newBinaryReader(fsMyfile);
//把文件指针重新定位到文件的开始
brMyfile.BaseStream.Seek(0,SeekOrigin.Begin);
byte[] bytes =brMyfile.ReadBytes(Convert.ToInt32(fsMyfile.Length.ToString()));
//关闭以上new的各个对象
brMyfile.Close();
return bytes;
}
/// <summary>
/// 按照参数设定对过大的源文件进行等比例缩放
/// </summary>
/// <param name="SourceFilePath">源文件路径</param>
/// <param name="Width">宽度</param>
/// <param name="Height">高度</param>
/// <param name="DestFilePath">缩放文件保存路径</param>
private void ResizeImageSize(string SourceFilePath, doubleWidth, double Height, string DestFilePath)
{
System.Drawing.Image image =System.Drawing.Image.FromFile(SourceFilePath);
//计算等比例缩放后图片大小
double NewWidth;
double NewHeight;
if (image.Width > image.Height)
{
NewWidth =Width;
NewHeight =image.Height * (NewWidth / image.Width);
}
else
{
NewHeight =Height;
NewWidth =image.Width * (NewHeight / image.Height);
}
if (NewWidth > Width)
{
NewWidth =Width;
}
if (NewHeight > Height)
{
NewHeight = Height;
}
//取得图片大小
System.Drawing.Size size = newSystem.Drawing.Size((int)NewWidth, (int)NewHeight);
//新建一个bmp图片
System.Drawing.Image bitmap = newSystem.Drawing.Bitmap(size.Width, size.Height);
System.Drawing.Graphics graphics =System.Drawing.Graphics.FromImage(bitmap);
graphics.InterpolationMode =System.Drawing.Drawing2D.InterpolationMode.High;
graphics.SmoothingMode =System.Drawing.Drawing2D.SmoothingMode.HighQuality;
graphics.Clear(System.Drawing.Color.White);
graphics.DrawImage(image, new System.Drawing.Rectangle(0,0, bitmap.Width, bitmap.Height), new System.Drawing.Rectangle(0, 0,image.Width, image.Height), System.Drawing.GraphicsUnit.Pixel);
try
{
bitmap.Save(DestFilePath);
}
catch
{ }
graphics.Dispose();
image.Dispose();
bitmap.Dispose();
}
//上传图片
protected void btnFilt_Click(object sender,EventArgs e)
{
//判断是否选择图片
if (this.FileUpload1.HasFile)
{
//stringname = this.FileUpload1.PostedFile.FileName;
//stringtype = name.Substring(name.LastIndexOf(".") + 1).ToLower();
bool PicOK =false;
stringstrExtension = Path.GetExtension(this.FileUpload1.FileName).ToLower();
stringpic_format =ConfigurationManager.AppSettings["pic_format"].ToString();
string[]Extensions = pic_format.Split('|');
for (int i =0; i < Extensions.Length; i++)
{
if (strExtension == Extensions[i])
{
PicOK = true;
break;
}
}
//判断图片的类型
if (!PicOK)
{
this.lblAlert.Text = jsOnClient.Alert("上传图片格式不对,只允许上传" + pic_format + "格式的图片!");return;
}
else
{
int NewWidth =Convert.ToInt32(ConfigurationManager.AppSettings["pic_Width"]);
int NewHeight = Convert.ToInt32(ConfigurationManager.AppSettings["pic_Height"]);
int FileMaxSize =Convert.ToInt32(ConfigurationManager.AppSettings["UploadFileMaxSize"]);
string pic_Path =ConfigurationManager.AppSettings["pic_Path"].ToString();
string pic_SFPath = ConfigurationManager.AppSettings["pic_SFPath"].ToString();
byte[] content = this.FileUpload1.FileBytes;
if (content.Length <= FileMaxSize)
{
string SourceFilePath = Server.MapPath(pic_Path) +Path.GetFileName(this.FileUpload1.PostedFile.FileName);
string DestFilePath = Server.MapPath(pic_SFPath) +Path.GetFileName(this.FileUpload1.PostedFile.FileName);
//上传原始图片
this.FileUpload1.SaveAs(SourceFilePath);
//图片缩放
ResizeImageSize(SourceFilePath, NewWidth, NewHeight, DestFilePath);
content = Returnbyte(DestFilePath);
//清除临时文件
if (File.Exists(SourceFilePath))
{
File.Delete(SourceFilePath);
}
if (File.Exists(DestFilePath))
{
File.Delete(DestFilePath);
}
int result = 0;
if (ViewState["type"].ToString() == "1") //实地勘验
{
Com.Netmarch.Model.SDKYWebPictureInfo webPictureInfo = newSDKYWebPictureInfo();
webPictureInfo.ID = 0;
webPictureInfo.JGJZBD_ID =Convert.ToInt32(ViewState["JGJZBD_ID"].ToString());
webPictureInfo.FileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
webPictureInfo.AttachDoc = content;
webPictureInfo.FStatus = 0;
result = sdkywebpicture.InsertSDKYWebPicture(webPictureInfo);
}
if (ViewState["type"].ToString() == "2") //市场调查
{
Com.Netmarch.Model.WebPictureInfo webPictureInfo = new WebPictureInfo();
webPictureInfo.ID = 0;
webPictureInfo.JGJZBD_ID = Convert.ToInt32(ViewState["JGJZBD_ID"].ToString());
webPictureInfo.FileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
webPictureInfo.AttachDoc = content;
webPictureInfo.FStatus = 0;
result = webpicture.InsertWebPicture(webPictureInfo);
}
if (result > 0)
{
//弹出上传成功的提示
//this.lblAlert.Text = jsOnClient.Alert("上传图片成功"); return;
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "","<script language='javascript'>alert('上传图片成功!');window.close();</script>");
}
else
{
this.lblAlert.Text = jsOnClient.Alert("上传图片失败!"); return;
}
}
else
{
this.lblAlert.Text = jsOnClient.Alert("上传图片不能超过2MB!");return;
}
}
}
else
{
//this.Page.ClientScript.RegisterStartupScript(this.GetType(), "","<script language='javascript'>alert('请先选择要上传的图片!');</script>");
this.lblAlert.Text = jsOnClient.Alert("请先选择要上传的图片!"); return;
}
}
}