北极之冰

asp.net生成缩略图

private void Button1_Click(object sender, System.EventArgs e)
  {
   this.Image1.ImageUrl= AutoOneImage(this.fileup.PostedFile,"Head_img");
  }
  public bool ThumbnailCallback()
   {
    return false;
   }
  private string AutoOneImage()
  {
   Graphics g=null;
    System.Drawing.Image upimage=null;
    System.Drawing.Image thumimg=null;
    System.Drawing.Image simage=null;
   int Maxwidth = 120;
   int Maxheight = 120;
    try
    {
    string extension = Path.GetExtension(file.FileName).ToUpper();
    string filename = DateTime.Now.ToString("yyyyMMddhhmmss");
 
    string smallpath = Server.MapPath(".")+"/images/Forum/"+smallImageSaveFolder+"/";
 
    System.Drawing.Image.GetThumbnailImageAbort callb =new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
    if(!Directory.Exists(smallpath))
    Directory.CreateDirectory(smallpath);
 

    Stream upimgfile = file.InputStream;
   
    upimage= System.Drawing.Image.FromStream(upimgfile); //上传的图片

   decimal width = upimage.Width;
   decimal height = upimage.Height;
   int newwidth = (int)width;
   int newheight = (int)height;
   
   double HeightWidth = Convert.ToDouble(height/width);
   double WidthHeight = Convert.ToDouble(width/height);

   if(height > Maxheight)
   {
    newheight = Maxheight;
    newwidth = (int)(Maxheight*WidthHeight);
   }

   if(width > Maxwidth)
   {
    newwidth = Maxwidth;
    newheight = (int)(Maxwidth*HeightWidth);
   }
   
    thumimg = upimage.GetThumbnailImage(newwidth,newheight,callb,IntPtr.Zero);  
    string thumpath = smallpath + filename + extension; //缩略图路径
    thumimg.Save(thumpath); 
   string imgurl = filename+extension;
   return imgurl; //返回缩略图路径名称
    }
    catch(Exception ex)
    {
     Response.Write(ex.Message);
    return null;
    }
    finally
    {
     if(g!=null)
     g.Dispose();
     if(thumimg!=null)
     thumimg.Dispose();
     if(upimage!=null)
     upimage.Dispose();
     if(simage!=null)
     simage.Dispose();
    }
}

posted on 2009-05-08 09:51  北极之冰  阅读(248)  评论(0)    收藏  举报