#region 上传图片生成缩略图
/// <summary>
/// 上传图片
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void btnUpload_Click(object sender, EventArgs e)
{
//检查上传文件的格式是否有效
if (this.fudPhoto.PostedFile.ContentType.ToLower().IndexOf("image") < )
{
Response.Write("<script>alert('上传图片格式无效!');window.location.href='LES_ApplyTopActivityAdd.aspx';</script>");
return;
}
string FileNmae;
string FileNameS;
string name = fudPhoto.PostedFile.FileName;//客户端文件路径
FileInfo file = new FileInfo(name);
string fileName = file.Name;
string ExtName = getFileExt(fileName).ToUpper();
//生成原图
Byte[] oFileByte = new byte[this.fudPhoto.PostedFile.ContentLength];
System.IO.Stream oStream = this.fudPhoto.PostedFile.InputStream;
System.Drawing.Image oImage = System.Drawing.Image.FromStream(oStream);
int towidth = ;//设置缩略图初始高度
int toheight = ;//设置缩略图初始宽度
int x = ;
int y = ;
int ow = oImage.Width;
int oh = oImage.Height;
if (ow == && ow == )
{
//按比例计算出缩略图的宽度和高度
if (((double)oImage.Width / (double)oImage.Height) > ((double)towidth / (double)toheight))
{
oh = oImage.Height;
ow = oImage.Height * towidth / toheight;
y = ;
x = (oImage.Width - ow) / ;
}
else
{
ow = oImage.Width;
oh = oImage.Width * toheight / towidth;
x = ;
y = (oImage.Height - oh) / ;
}
//生成缩略原图
Bitmap tImage = new Bitmap(towidth, toheight);
Graphics g = Graphics.FromImage(tImage);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; //设置高质量插值法
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;//设置高质量,低速度呈现平滑程度
g.Clear(Color.Transparent); //清空画布并以透明背景色填充
g.DrawImage(oImage, new Rectangle(, , towidth, toheight), new Rectangle(, , ow, oh), GraphicsUnit.Pixel);
FileNmae = DateTime.Now.ToShortDateString().Replace("-", "") + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + "." + ExtName; //保存原图的物理路径
string oFullName = Server.MapPath("/uploadfiles//" + FileNmae);
FileNameS = FileNmae + "-S" + ".JPG"; //保存缩略图的物理路径
string tFullName = Server.MapPath("/uploadfiles//" + FileNameS);
try
{
//以JPG格式保存图片
oImage.Save(oFullName, System.Drawing.Imaging.ImageFormat.Jpeg);
tImage.Save(tFullName, System.Drawing.Imaging.ImageFormat.Jpeg);
//lbMessage.Text = "提示:文件”" + FileNmae + "“成功上传,并生成”" + FileNameS + "“缩略图,文件类型为:" +
// fudPhoto.PostedFile.ContentType + ",文件大小为:" + fudPhoto.PostedFile.ContentLength + "B";
lbMessage.Text = "提示:文件成功上传,并生成”" + FileNameS + "“缩略图!";
string PIC = FileNmae;
ViewState["pic"] = PIC;
}
catch (Exception ex)
{
throw ex;
}
finally
{
//释放资源
oImage.Dispose();
g.Dispose();
tImage.Dispose();
}
}
else
{
lbMessage.Text = "提示:图片的尺寸应该是640x640";
}
}
private string getFileExt(string fileName)
{
if (fileName.IndexOf(".") == -)
return "";
string[] temp = fileName.Split('.');
return temp[temp.Length - ].ToLower();
}
#endregion
}
如图效果图: