最近碰到这样一个需求:把图片保存到数据库中,然后作为上传人的头像之类的。本着程序员的优良“惰性”Google了一把,找到了一大把一大把代码,试了很多号称能得到清晰缩略图的,结果就不用说了。最终在一开源项目中找到了解决办法,为了让后来人免受我所受过的煎熬,所以放出代码!
写一个上传页面:
<%
...
@Pagelanguage="c#"Codebehind="UploadPictureConvertTo.aspx.cs"AutoEventWireup="false"Inherits="PicturesToDB.UI.UploadPictureConvertTo"
%>
<! DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.0Transitional//EN" >
< HTML >
< HEAD >
< title > UploadPicture </ title >
< meta name ="GENERATOR" Content ="MicrosoftVisualStudio.NET7.1" >
< meta name ="CODE_LANGUAGE" Content ="C#" >
< meta name ="vs_defaultClientScript" content ="JavaScript" >
< meta name ="vs_targetSchema" content ="http://schemas.microsoft.com/intellisense/ie5" >
< script language ="javascript" > ...
functionShowImage(value,img)
...{
//alert(value);该脚本来源于网络
//检测盘符
//alert(value.indexOf(':'));
//检测文件是否有扩展名
//alert(value.length-value.lastIndexOf('.'));
//取文件扩展名
//alert(value.substr(value.length-3,3));
//检测文件扩展名是否合法
//alert(CheckExt(value.substr(value.length-3,3)));
if(value.length>5&&value.indexOf(':')==1&&(value.length-value.lastIndexOf('.'))==4&&CheckExt(value.substr(value.length-3,3)))
...{
img.src=value;
img.alt="本地图片预览";
img.style.visibility="visible";
}
else
...{
img.style.visibility="hidden";
}
}
//检查扩展名是否合法,合法返回True
functionCheckExt(ext)
...{
//这里设置允许的扩展名
varAllowExt="jpg|gif|jpeg|png|bmp";
varExtOK=false;
varArrayExt;
if(AllowExt.indexOf('|')!=-1)
...{
ArrayExt=AllowExt.split('|');
for(i=0;i<ArrayExt.length;i++)
...{
if(ext.toLowerCase()==ArrayExt[i])
...{
ExtOK=true;
break;
}
}
}
else
...{
ArrayExt=AllowExt;
if(ext.toLowerCase()==ArrayExt)
...{
ExtOK=true;
}
}
returnExtOK;
}
</ script >
</ HEAD >
< body MS_POSITIONING ="GridLayout" >
< form id ="Form1" method ="post" runat ="server" enctype ="multipart/form-data" >
< table >
< tr >
< td colspan ="2" >< img id ="img" STYLE ="VISIBILITY:hidden" ></ td >
</ tr >
< tr >
< td > 请选择上传图片 </ td >
< td >< input id ="PictureFile" name ="PictureFile" type ="file" onchange ="javascript:ShowImage(this.value,document.getElementById('img'))"
runat ="server" ></ td >
</ tr >
< tr >
< td > 描述 </ td >
< td >
< asp:TextBox id ="TextBox1" runat ="server" ></ asp:TextBox ></ td >
</ tr >
< tr >
< td colspan ="2" align ="center" >
< asp:Button id ="Button1" runat ="server" Text ="提交" ></ asp:Button ></ td >
</ tr >
</ table >
</ form >
</ body >
</ HTML >
<! DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.0Transitional//EN" >
< HTML >
< HEAD >
< title > UploadPicture </ title >
< meta name ="GENERATOR" Content ="MicrosoftVisualStudio.NET7.1" >
< meta name ="CODE_LANGUAGE" Content ="C#" >
< meta name ="vs_defaultClientScript" content ="JavaScript" >
< meta name ="vs_targetSchema" content ="http://schemas.microsoft.com/intellisense/ie5" >
< script language ="javascript" > ...
functionShowImage(value,img)
...{
//alert(value);该脚本来源于网络
//检测盘符
//alert(value.indexOf(':'));
//检测文件是否有扩展名
//alert(value.length-value.lastIndexOf('.'));
//取文件扩展名
//alert(value.substr(value.length-3,3));
//检测文件扩展名是否合法
//alert(CheckExt(value.substr(value.length-3,3)));
if(value.length>5&&value.indexOf(':')==1&&(value.length-value.lastIndexOf('.'))==4&&CheckExt(value.substr(value.length-3,3)))
...{
img.src=value;
img.alt="本地图片预览";
img.style.visibility="visible";
}
else
...{
img.style.visibility="hidden";
}
}
//检查扩展名是否合法,合法返回True
functionCheckExt(ext)
...{
//这里设置允许的扩展名
varAllowExt="jpg|gif|jpeg|png|bmp";
varExtOK=false;
varArrayExt;
if(AllowExt.indexOf('|')!=-1)
...{
ArrayExt=AllowExt.split('|');
for(i=0;i<ArrayExt.length;i++)
...{
if(ext.toLowerCase()==ArrayExt[i])
...{
ExtOK=true;
break;
}
}
}
else
...{
ArrayExt=AllowExt;
if(ext.toLowerCase()==ArrayExt)
...{
ExtOK=true;
}
}
returnExtOK;
}
</ script >
</ HEAD >
< body MS_POSITIONING ="GridLayout" >
< form id ="Form1" method ="post" runat ="server" enctype ="multipart/form-data" >
< table >
< tr >
< td colspan ="2" >< img id ="img" STYLE ="VISIBILITY:hidden" ></ td >
</ tr >
< tr >
< td > 请选择上传图片 </ td >
< td >< input id ="PictureFile" name ="PictureFile" type ="file" onchange ="javascript:ShowImage(this.value,document.getElementById('img'))"
runat ="server" ></ td >
</ tr >
< tr >
< td > 描述 </ td >
< td >
< asp:TextBox id ="TextBox1" runat ="server" ></ asp:TextBox ></ td >
</ tr >
< tr >
< td colspan ="2" align ="center" >
< asp:Button id ="Button1" runat ="server" Text ="提交" ></ asp:Button ></ td >
</ tr >
</ table >
</ form >
</ body >
</ HTML >
上传按钮的Click事件,以及生成缩略图的方法
private
void
Button1_Click(
object
sender,System.EventArgse)
... {
//没有做文件类型检测,自己加上可以参考清清月儿的Blog
//http://blog.csdn.net/21aspnet/archive/2007/04/01/1548696.aspx
HttpPostedFilepicture=PictureFile.PostedFile;
PictureLength=picture.ContentLength;
try
...{
if(PictureLength==0)
...{
Response.Write("<scriptlanguage=javascript>alert('请选择上传文件');</script>");
}
else
...{
StreamPictureStram=picture.InputStream;
MemoryStreamReduceStream=newMemoryStream();
ReduceStream=ResizeImageFile(PictureStram);
Byte[]PictureByte=ReduceStream.ToArray();
stringstrConn=@"DataSource=localhost;InitialCatalog=CommonCompontTest;UserID=sa;Pwd=sa";
SqlConnectionsqlConn=newSqlConnection(strConn);
stringsqlCommand=@"INSERTINTO[PicturnsTable]([PictureBinary],[PictureType],[PictureDes],[PiacureSize])
VALUES(@PictureBinary,@PictureDes,@PiacureSize)";
SqlCommandsqlCMD=newSqlCommand(sqlCommand,sqlConn);
sqlCMD.Parameters.Add("@PictureBinary",SqlDbType.Binary).Value=PictureByte;
sqlCMD.Parameters.Add("@PictureDes",SqlDbType.VarChar,200).Value=TextBox1.Text.Trim();
sqlCMD.Parameters.Add("@PiacureSize",SqlDbType.Int).Value=PictureByte.Length;
sqlConn.Open();
sqlCMD.ExecuteNonQuery();
sqlConn.Close();
Response.Write(@"<scriptlanguage=javascript>alert('文件上传功');window.location.href='UploadPictureConvertTo.aspx';</script>");
//Response.Redirect("UploadPicture.aspx");
}
}
catch(Exceptionex)
...{
Console.Write(ex.Message);
}
}
// 生成缩略图的代码
private static MemoryStreamResizeImageFile(Streamstream)
... {
SizenewSize=newSize(320,240);
using(System.Drawing.ImageoldImage=System.Drawing.Image.FromStream(stream))
...{
using(BitmapnewImage=newBitmap(newSize.Width,newSize.Height,PixelFormat.Format24bppRgb))
...{
using(Graphicscanvas=Graphics.FromImage(newImage))
...{
canvas.SmoothingMode=SmoothingMode.AntiAlias;
canvas.InterpolationMode=InterpolationMode.HighQualityBicubic;
canvas.PixelOffsetMode=PixelOffsetMode.HighQuality;
canvas.DrawImage(oldImage,newRectangle(newPoint(0,0),newSize));
MemoryStreamm=newMemoryStream();
newImage.Save(m,ImageFormat.Jpeg);
returnm;
}
}
}
}
... {
//没有做文件类型检测,自己加上可以参考清清月儿的Blog
//http://blog.csdn.net/21aspnet/archive/2007/04/01/1548696.aspx
HttpPostedFilepicture=PictureFile.PostedFile;
PictureLength=picture.ContentLength;
try
...{
if(PictureLength==0)
...{
Response.Write("<scriptlanguage=javascript>alert('请选择上传文件');</script>");
}
else
...{
StreamPictureStram=picture.InputStream;
MemoryStreamReduceStream=newMemoryStream();
ReduceStream=ResizeImageFile(PictureStram);
Byte[]PictureByte=ReduceStream.ToArray();
stringstrConn=@"DataSource=localhost;InitialCatalog=CommonCompontTest;UserID=sa;Pwd=sa";
SqlConnectionsqlConn=newSqlConnection(strConn);
stringsqlCommand=@"INSERTINTO[PicturnsTable]([PictureBinary],[PictureType],[PictureDes],[PiacureSize])
VALUES(@PictureBinary,@PictureDes,@PiacureSize)";
SqlCommandsqlCMD=newSqlCommand(sqlCommand,sqlConn);
sqlCMD.Parameters.Add("@PictureBinary",SqlDbType.Binary).Value=PictureByte;
sqlCMD.Parameters.Add("@PictureDes",SqlDbType.VarChar,200).Value=TextBox1.Text.Trim();
sqlCMD.Parameters.Add("@PiacureSize",SqlDbType.Int).Value=PictureByte.Length;
sqlConn.Open();
sqlCMD.ExecuteNonQuery();
sqlConn.Close();
Response.Write(@"<scriptlanguage=javascript>alert('文件上传功');window.location.href='UploadPictureConvertTo.aspx';</script>");
//Response.Redirect("UploadPicture.aspx");
}
}
catch(Exceptionex)
...{
Console.Write(ex.Message);
}
}
// 生成缩略图的代码
private static MemoryStreamResizeImageFile(Streamstream)
... {
SizenewSize=newSize(320,240);
using(System.Drawing.ImageoldImage=System.Drawing.Image.FromStream(stream))
...{
using(BitmapnewImage=newBitmap(newSize.Width,newSize.Height,PixelFormat.Format24bppRgb))
...{
using(Graphicscanvas=Graphics.FromImage(newImage))
...{
canvas.SmoothingMode=SmoothingMode.AntiAlias;
canvas.InterpolationMode=InterpolationMode.HighQualityBicubic;
canvas.PixelOffsetMode=PixelOffsetMode.HighQuality;
canvas.DrawImage(oldImage,newRectangle(newPoint(0,0),newSize));
MemoryStreamm=newMemoryStream();
newImage.Save(m,ImageFormat.Jpeg);
returnm;
}
}
}
}
数据库表结构很简单,这里就不说了
然后就是获取图片的页面,写得很简单,将就着看哈
private
void
Page_Load(
object
sender,System.EventArgse)
... {
//在此处放置用户代码以初始化页面
intPictureID=Convert.ToInt32(Request.Params["PictureID"]);//ImgID为图片ID
//建立数据库链接
stringstrConn=@"DataSource=localhost;InitialCatalog=CommonCompontTest;UserID=sa;Pwd=sa";
SqlConnectionsqlConn=newSqlConnection(strConn);
StringSqlCmd="SELECT[PictureID],[PictureBinary],PictureDes],[PiacureSize]FROM.[PicturnsTable]wherePictureID=@PictureID";
SqlCommandSQLCmd=newSqlCommand(SqlCmd,sqlConn);
SQLCmd.Parameters.Add("@PictureID",SqlDbType.Int).Value=PictureID;
sqlConn.Open();
SqlDataReaderSqlReader=SQLCmd.ExecuteReader();
SqlReader.Read();
//输出图象文件二进制数制
Response.OutputStream.Write((byte[])SqlReader["PictureBinary"],0,(int)SqlReader["PiacureSize"]);
Response.End();
sqlConn.Close();
//很简单吧^_^
}
... {
//在此处放置用户代码以初始化页面
intPictureID=Convert.ToInt32(Request.Params["PictureID"]);//ImgID为图片ID
//建立数据库链接
stringstrConn=@"DataSource=localhost;InitialCatalog=CommonCompontTest;UserID=sa;Pwd=sa";
SqlConnectionsqlConn=newSqlConnection(strConn);
StringSqlCmd="SELECT[PictureID],[PictureBinary],PictureDes],[PiacureSize]FROM.[PicturnsTable]wherePictureID=@PictureID";
SqlCommandSQLCmd=newSqlCommand(SqlCmd,sqlConn);
SQLCmd.Parameters.Add("@PictureID",SqlDbType.Int).Value=PictureID;
sqlConn.Open();
SqlDataReaderSqlReader=SQLCmd.ExecuteReader();
SqlReader.Read();
//输出图象文件二进制数制
Response.OutputStream.Write((byte[])SqlReader["PictureBinary"],0,(int)SqlReader["PiacureSize"]);
Response.End();
sqlConn.Close();
//很简单吧^_^
}
查看图片的页面就用个Gridview就可以了,更简单的就是,这样写在VS IDE中直接就可以看到了,麻烦就是每次都要改^_^
<%
@Pagelanguage
=
"
c#
"
Codebehind
=
"
ShowPicture.aspx.cs
"
AutoEventWireup
=
"
false
"
Inherits
=
"
PicturesToDB.UI.ShowPicture
"
%>
<! DOCTYPEHTMLPUBLIC " -//W3C//DTDHTML4.0Transitional//EN " >
< HTML >
< HEAD >
< title > ShowPicture </ title >
< metaname = " GENERATOR " Content = " MicrosoftVisualStudio.NET7.1 " >
< metaname = " CODE_LANGUAGE " Content = " C# " >
< metaname = " vs_defaultClientScript " content = " JavaScript " >
< metaname = " vs_targetSchema " content = " http://schemas.microsoft.com/intellisense/ie5 " >
</ HEAD >
< bodyMS_POSITIONING = " GridLayout " >
< formid = " Form1 " method = " post " runat = " server " >
< imgsrc = " GetThePicture.aspx?PictureID=29 " >
</ form >
</ body >
</ HTML >
<! DOCTYPEHTMLPUBLIC " -//W3C//DTDHTML4.0Transitional//EN " >
< HTML >
< HEAD >
< title > ShowPicture </ title >
< metaname = " GENERATOR " Content = " MicrosoftVisualStudio.NET7.1 " >
< metaname = " CODE_LANGUAGE " Content = " C# " >
< metaname = " vs_defaultClientScript " content = " JavaScript " >
< metaname = " vs_targetSchema " content = " http://schemas.microsoft.com/intellisense/ie5 " >
</ HEAD >
< bodyMS_POSITIONING = " GridLayout " >
< formid = " Form1 " method = " post " runat = " server " >
< imgsrc = " GetThePicture.aspx?PictureID=29 " >
</ form >
</ body >
</ HTML >
代码就这样,希望能被需要的人Google到 呵呵