您的位置:首页 > 编程语言 > ASP

asp.net上传图片自动生成缩略图功能代码

2012-02-14 17:27 941 查看
if (FileUpload1.FileName.ToString() == "")
{
Label3.Text = "请选择图片!";
}
else
{
Boolean FileOK = false;
if (this.FileUpload1.HasFile)
{
// 限制上传图片小于 2M
if (FileUpload1.PostedFile.ContentLength <= 2097152)
{
// 图片 Guid 重命名
Session["WorkingImage"] = Guid.NewGuid().ToString() + Path.GetExtension(FileUpload1.FileName.ToString()).ToLower();
String FileExtension = Path.GetExtension(Session["WorkingImage"].ToString()).ToLower();
String[] allowedExtensions = { ".png", ".jpeg", ".jpg", ".gif" };
for (int i = 0; i < allowedExtensions.Length; i++)
{
if (FileExtension == allowedExtensions[i])
{
FileOK = true;
}
}
}
// 上传图片大于 2M 警告
else
{
FileOK = false;
Response.Write("<script language=javascript>alert('图片不要超过 2M 大小!');window.location.href=window.location.href;</script>");
}
}
if (FileOK)
{
try
{
//生成原图
Byte[] oFileByte = new byte[this.FileUpload1.PostedFile.ContentLength];
System.IO.Stream oStream = this.FileUpload1.PostedFile.InputStream;
System.Drawing.Image oImage = System.Drawing.Image.FromStream(oStream);

int oWidth = oImage.Width; //原图宽度
int oHeight = oImage.Height; //原图高度
int tWidth; //缩略图宽度
int tHeight; //缩略图高度

//按比例计算出缩略图的宽度和高度
if (oWidth >= oHeight)
{
tWidth = 300;
tHeight = (int)Math.Floor(Convert.ToDouble(oHeight) * (Convert.ToDouble(tWidth) / Convert.ToDouble(oWidth)));
}
else
{
tHeight = 300;
tWidth = (int)Math.Floor(Convert.ToDouble(oWidth) * (Convert.ToDouble(tHeight) / Convert.ToDouble(oHeight)));
}
//生成缩略原图
Bitmap tImage = new Bitmap(tWidth, tHeight);
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(0, 0, tWidth, tHeight), new Rectangle(0, 0, oWidth, oHeight), GraphicsUnit.Pixel);

string fullFileName = this.FileUpload1.PostedFile.FileName.ToString();
fullFileName = fullFileName.Remove(fullFileName.LastIndexOf('.'));
string filename = fullFileName.Substring(fullFileName.LastIndexOf("\\") + 1);
//存储路径
string strLocation = path.ToString();
string tFullName = strLocation + Session["WorkingImage"].ToString();
try
{
// 上传缩略
tImage.Save(tFullName, System.Drawing.Imaging.ImageFormat.Jpeg);
//输出上传成功提示并显示保存路径
TextBox3.Text = "uploadfiles/product/" + Session["WorkingImage"].ToString();
// pic_upload.Visible = false;
// pic_crop.Visible = true;
// 读取缩略图
path = "../uploadfiles/product/" + Session["WorkingImage"].ToString();

}
catch (Exception)
{
Response.Write("<script language=javascript>alert('上传失败,请重试!');window.location.href=window.location.href;</script>");
}
finally
{
//释放资源
oImage.Dispose();
g.Dispose();
tImage.Dispose();
}
}
catch (Exception)
{
Response.Write("<script language=javascript>alert('上传失败,请重试!');window.location.href=window.location.href;</script>");
}
}
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: