图片上传及自动处理为指定大小
一. 图片上传和读取
首先建立数据表名称为image,有两个字段name和image数据类型分别为varchar和image,image类型存放的是二进制数据.
第一步当然是上传图片并把它转化成byte[],我们用的是.net2.0可以直接用FileUpLoad控件来实现.即
byte[] fileData = this.FileUpload1.FileBytes;这样图片就转换成了byte[],在这里可以发现在转换byte[]时我们只需FileUpLoad的一个方法就实现了,不用像1.1那样用以下方法来实现:
byte[] fileData = this.FileUpload1.FileBytes;这样图片就转换成了byte[],在这里可以发现在转换byte[]时我们只需FileUpLoad的一个方法就实现了,不用像1.1那样用以下方法来实现:
public byte[] getBytes(string filePath)
{
System.IO.FileStream fs = new System.IO.FileStream(filePath, System.IO.FileMode.Open);
byte[] imgData = new byte[fs.Length];
fs.Read(imgData, 0, (int)fs.Length);
return imgData;
}
而后就是向数据库提交数据了完整代码如下: {
System.IO.FileStream fs = new System.IO.FileStream(filePath, System.IO.FileMode.Open);
byte[] imgData = new byte[fs.Length];
fs.Read(imgData, 0, (int)fs.Length);
return imgData;
}
string type = FUp.FileName.Substring(FUp.FileName.LastIndexOf(".") + 1);
int length = FUp.PostedFile.ContentLength;
Response.Write(length);
string flname =DateTime.Now.ToString("yyyyMMddmmss");
Random r = new Random();
string d=r.Next(100, 1000).ToString();
flname = flname + d+"."+type;
if (type=="jpg" || type == "JPG" || type == "gif" || type == "GIF" || type == "bmp" || type == "BMP")
{
if (length < 1073741)
{
byte[] fileData = this.FUp.FileBytes;
string sql = "insert into image(name,image) s (@name,@img)";
string strconn = System.Configuration.ConfigurationManager.ConnectionStrings["newsConnectionString"].ToString();
SqlConnection sqlConn = new SqlConnection(strconn);
SqlCommand sqlComm = new SqlCommand(sql, sqlConn);
sqlComm.Parameters.Add("@name", SqlDbType.VarChar);//添加参数
sqlComm.Parameters["@name"]. = flname;//为参数赋值
sqlComm.Parameters.Add("@img", SqlDbType.Image);//添加参数
sqlComm.Parameters["@img"]. = fileData;//为参数赋值
sqlConn.Open();
sqlComm.ExecuteNonQuery();
sqlConn.Close();
}
else {
Response.Write("文件应不大于1M");
}
}
else {
Response.Write("文件格式不正确");
}
注意代码中有颜色的部分必须采用参数的形式而int length = FUp.PostedFile.ContentLength;
Response.Write(length);
string flname =DateTime.Now.ToString("yyyyMMddmmss");
Random r = new Random();
string d=r.Next(100, 1000).ToString();
flname = flname + d+"."+type;
if (type=="jpg" || type == "JPG" || type == "gif" || type == "GIF" || type == "bmp" || type == "BMP")
{
if (length < 1073741)
{
byte[] fileData = this.FUp.FileBytes;
string sql = "insert into image(name,image) s (@name,@img)";
string strconn = System.Configuration.ConfigurationManager.ConnectionStrings["newsConnectionString"].ToString();
SqlConnection sqlConn = new SqlConnection(strconn);
SqlCommand sqlComm = new SqlCommand(sql, sqlConn);
sqlComm.Parameters.Add("@name", SqlDbType.VarChar);//添加参数
sqlComm.Parameters["@name"]. = flname;//为参数赋值
sqlComm.Parameters.Add("@img", SqlDbType.Image);//添加参数
sqlComm.Parameters["@img"]. = fileData;//为参数赋值
sqlConn.Open();
sqlComm.ExecuteNonQuery();
sqlConn.Close();
}
else {
Response.Write("文件应不大于1M");
}
}
else {
Response.Write("文件格式不正确");
}
string sql = "insert into image(name,image) s ('"+flname+"','"+fileData+"')";
是不正确的,因为如果采用这种形式向数据库中写入二进制流时,会丢失数据(具体原因不明,我也是在这种情况不成功后才采取的参数方法的).
然后就是如何读取了,我们先建立一个image.aspx新页用来显示图片,后台代码如下
int id = Convert.ToInt32(Request.QueryString["id"].ToString());
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings ["newsConnectionString"].ConnectionString);
con.Open();
SqlCommand com = new SqlCommand("select image from image where id="+id, con);
byte[] fileData = (byte[])com.ExecuteScalar();
con.Close();
//读取二进制流
Response.BinaryWrite(fileData);
Response.End();
在主页面上我们用DataList1控件来显示数据HTML代码如下:SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings ["newsConnectionString"].ConnectionString);
con.Open();
SqlCommand com = new SqlCommand("select image from image where id="+id, con);
byte[] fileData = (byte[])com.ExecuteScalar();
con.Close();
//读取二进制流
Response.BinaryWrite(fileData);
Response.End();
<asp:DataList ID="DataList1" runat="server" DataSourceID="SqlDataSource1" RepeatDirection=Horizontal RepeatColumns=4><ItemTemplate><a href="imageshow.aspx?id=<%#Eval("id") %>"><img src="imageshow.aspx?id=<%#Eval("id") %>" width="60px" height="80px"/></a></ItemTemplate></asp:DataList>
(注意代码中有颜色的部分)
二. 图片存放功能扩展(指定大小存放)
在上面存放图片的基础上,加上转换图片大小的方法就可以,转换图片大小的方法有两个分别为: ResizeImageFile和CalculateDimensions,后一个的是得到一个所要求图片长和宽的一个矩形,前一个方法的功能是:将得到的新图片转换成二进制流。具体内容如下:
/// <summary>
/// 得到新图片
/// </summary>
/// <param name="imageFile">上传图片的二进制流</param>
/// <param name="newhigh">所指定图片的高</param>
/// <param name="newwith">所指定图片的宽</param>
/// <returns>新图片所生成的二进制流</returns>
private static byte[] ResizeImageFile(byte[] imageFile, int newhigh,int newwith)
{
using (System.Drawing.Image oldImage = System.Drawing.Image.FromStream(new MemoryStream(imageFile)))
{
Size newSize = CalculateDimensions(oldImage.Size, newhigh,newwith);
using (Bitmap newImage = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format24bppRgb))
{
using (Graphics canvas = Graphics.FromImage(newImage))
{
canvas.SmoothingMode = SmoothingMode.AntiAlias;
canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
canvas.PixelOffsetMode = PixelOffsetMode.HighQuality;
canvas.DrawImage(oldImage, new Rectangle(new Point(0, 0), newSize));
MemoryStream m = new MemoryStream();
newImage.Save(m, ImageFormat.Jpeg);
return m.GetBuffer();
}
}
}
}
/// <summary>
/// 得到一个矩形(宽高分别为指定高和宽)
/// </summary>
/// <param name="newhigh">所指定图片的高</param>
/// <param name="newwith">所指定图片的宽</param>
/// <returns>一个新矩形</returns>
private static Size CalculateDimensions(int newhigh, int newwith)
{
Size newSize = new Size();
newSize.Height = newhigh;
newSize.Width = newwith;
return newSize;
}
调用方法如下:
/// <summary>
/// 向数据库中添加新图的二进制流
/// </summary>
/// <param name="flname">图的名称</param>
/// <param name="fileData">上传图片生成的二进制流</param>
/// <param name="newhigh">指定新图片的高</param>
/// <param name="newwith">指定新图片的宽</param>
public static void AddPhoto(string flname, byte[] fileData, int newhigh, int newwith)
{
string sql = "insert into image(name,image) s (@name,@img)";
string strconn = System.Configuration.ConfigurationManager.ConnectionStrings["newsConnectionString"].ToString();
SqlConnection sqlConn = new SqlConnection(strconn);
SqlCommand sqlComm = new SqlCommand(sql, sqlConn);
sqlComm.Parameters.Add("@name", SqlDbType.VarChar);//添加参数
sqlComm.Parameters["@name"]. = flname;//为参数赋值
sqlComm.Parameters.Add("@img", SqlDbType.Image);//添加参数
sqlComm.Parameters["@img"]. = ResizeImageFile(fileData, newhigh, newwith);//为参数赋值
sqlConn.Open();
sqlComm.ExecuteNonQuery();
sqlConn.Close();
}
/// 得到新图片
/// </summary>
/// <param name="imageFile">上传图片的二进制流</param>
/// <param name="newhigh">所指定图片的高</param>
/// <param name="newwith">所指定图片的宽</param>
/// <returns>新图片所生成的二进制流</returns>
private static byte[] ResizeImageFile(byte[] imageFile, int newhigh,int newwith)
{
using (System.Drawing.Image oldImage = System.Drawing.Image.FromStream(new MemoryStream(imageFile)))
{
Size newSize = CalculateDimensions(oldImage.Size, newhigh,newwith);
using (Bitmap newImage = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format24bppRgb))
{
using (Graphics canvas = Graphics.FromImage(newImage))
{
canvas.SmoothingMode = SmoothingMode.AntiAlias;
canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
canvas.PixelOffsetMode = PixelOffsetMode.HighQuality;
canvas.DrawImage(oldImage, new Rectangle(new Point(0, 0), newSize));
MemoryStream m = new MemoryStream();
newImage.Save(m, ImageFormat.Jpeg);
return m.GetBuffer();
}
}
}
}
/// <summary>
/// 得到一个矩形(宽高分别为指定高和宽)
/// </summary>
/// <param name="newhigh">所指定图片的高</param>
/// <param name="newwith">所指定图片的宽</param>
/// <returns>一个新矩形</returns>
private static Size CalculateDimensions(int newhigh, int newwith)
{
Size newSize = new Size();
newSize.Height = newhigh;
newSize.Width = newwith;
return newSize;
}
调用方法如下:
/// <summary>
/// 向数据库中添加新图的二进制流
/// </summary>
/// <param name="flname">图的名称</param>
/// <param name="fileData">上传图片生成的二进制流</param>
/// <param name="newhigh">指定新图片的高</param>
/// <param name="newwith">指定新图片的宽</param>
public static void AddPhoto(string flname, byte[] fileData, int newhigh, int newwith)
{
string sql = "insert into image(name,image) s (@name,@img)";
string strconn = System.Configuration.ConfigurationManager.ConnectionStrings["newsConnectionString"].ToString();
SqlConnection sqlConn = new SqlConnection(strconn);
SqlCommand sqlComm = new SqlCommand(sql, sqlConn);
sqlComm.Parameters.Add("@name", SqlDbType.VarChar);//添加参数
sqlComm.Parameters["@name"]. = flname;//为参数赋值
sqlComm.Parameters.Add("@img", SqlDbType.Image);//添加参数
sqlComm.Parameters["@img"]. = ResizeImageFile(fileData, newhigh, newwith);//为参数赋值
sqlConn.Open();
sqlComm.ExecuteNonQuery();
sqlConn.Close();
}