51代码网ORACLEMYSQLSQL SERVER其它数据库java/jspasp/asp.netC/C++/VC++APP应用其它语言服务器应用
您现在的位置: 51代码网 >> asp.net >> 文章正文

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

更新时间:2012-2-16:  来源:51代码网

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);

[1] [2] 下一页

  • 上一篇文章:
  • 下一篇文章: 没有了
  • 赞助商链接
    推荐文章
  • 此栏目下没有推荐文章
  • {
    设为首页 | 加入收藏 | 友情链接 | 网站地图 | 联系站长 |