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.Data.SqlClient;
using System.Drawing;
//using System.IO;
public partial class Adi_Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
SqlConnection conn = new SqlConnection("server=.;database=aspnetdb;uid=sa;pwd=qwe2323478");
SqlCommand Mycomm = new SqlCommand();
protected void Dupload_Click(object sender, EventArgs e)
{
Boolean fileup=false;
string path = Server.MapPath("~/modules/dtimage/");
string filegeshi=System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();
string[] allowgeshi ={ ".jpg", ".gif", ".jpge", ".png" };
if (FileUpload1 .HasFile)
{
for (int i = 0; i < allowgeshi.Length; i++)
{
if (filegeshi == allowgeshi[i])
{
fileup = true;
}
}
}
if(fileup==true)
{
try
{
FileUpload upfile = FileUpload1;
System.IO.Stream Filestream = upfile.FileContent;
//调用Doit函数生成缩略图并放在另一个文件夹里。
Doit(Filestream,Server.MapPath("../modules/image/"+FileUpload1.FileName));
FileUpload1.SaveAs(path + FileUpload1.FileName);
MsgD.Text="上传成功";
}
catch(Exception ex)
{
MsgD.Text="发生错误!";
}
}
else
{
MsgD.Text="不能上传这种格式!";
}
}
public bool Doit(System.IO.Stream stream, string savepath)
{
System.Drawing.Image img = System.Drawing.Image.FromStream(stream);
int img_w = Convert.ToInt32(img.Width);
int imgx_h = Convert.ToInt32(img.Height);
System.Drawing.Bitmap simage = new System.Drawing.Bitmap(150, 150);
Graphics g = System.Drawing.Graphics.FromImage(simage);
g.Clear(Color.White);
if (img == null)
{
return false;
}
if (img_w <= 150 && imgx_h <= 150)
{
/*Graphics.DrawImage(Image img ,RectangleF Rf ) RectangleF为固定大小跟坐标画图片,有4个Int的参数,也有4个float参数的
的重载,其他重载参见MSDN*/
g.DrawImage(img, new RectangleF(Convert.ToInt32((150 - img_w) / 2), Convert.ToInt32((150 - imgx_h) / 2), img_w, imgx_h));
simage.Save(savepath, System.Drawing.Imaging.ImageFormat.Jpeg);
return true;
}
else
{
if (img_w >= imgx_h)
{
//计算缩放比例,计算出缩放后的高度
imgx_h = imgx_h * 150 / img_w;
g.DrawImage(img, new RectangleF(0, Convert.ToInt32((150 - imgx_h) / 2), 150, imgx_h));
simage.Save(savepath, System.Drawing.Imaging.ImageFormat.Jpeg);
//g.Save(savepath, System.Drawing.Imaging.ImageFormat.Jpeg);
return true;
}
else if (img_w < imgx_h)
{
img_w = img_w * 150 / imgx_h;
g.DrawImage(img, new RectangleF(Convert.ToInt32((150 - img_w) / 2), 0, img_w, imgx_h));
simage.Save(savepath, System.Drawing.Imaging.ImageFormat.Jpeg);
return true;
}
}
return false;
}
}
-----------------------------------------------------------------
代码在发布的时候我删除了一些 数据库操作的部分,没测试代码的完整性。仅供参考