asp.net 缩略图--源码--调试成功

     private static Size NewSize(int maxWidth,int maxHeight,int Width,int Height)
  {
   double w=0.0;
   double h=0.0;
   double sw=Convert.ToDouble(Width);
   double sh=Convert.ToDouble(Height);
   double mw=Convert.ToDouble(maxWidth);
   double mh=Convert.ToDouble(maxHeight);
 
   if(sw<mw && sh<mh)//如果maxWidth和maxHeight大于源图像,则缩略图的长和高不变
   {
    w=sw;
    h=sh;
   }
   else if((sw/sh)>(mw/mh))
   {
    w=maxWidth;
    h=(w*sh)/sw;
   }
   else
   {
    h=maxHeight;
    w=(h*sw)/sh;
   }
   return new Size(Convert.ToInt32(w),Convert.ToInt32(h));
  }


  public  void SendSmallImage(string filename,string newfile ,int maxHeight,int maxWidth)
  {
   System.Drawing.Image img=System.Drawing.Image.FromFile(filename);//源图像的信息
   System.Drawing.Imaging.ImageFormat thisformat=img.RawFormat; //源图像的格式

   Size newSize=NewSize(maxWidth,maxHeight,img.Width,img.Height); //返回调整后的图像Width与Height
   Bitmap outBmp=new Bitmap(newSize.Width,newSize.Height);
   Graphics g=Graphics.FromImage(outBmp);
   //设置画布的描绘质量
   g.CompositingQuality =CompositingQuality.HighQuality;
   g.SmoothingMode=SmoothingMode.HighQuality;
   g.InterpolationMode=InterpolationMode.HighQualityBicubic;
   g.DrawImage(img,new Rectangle(0,0,newSize.Width,newSize.Height),0,0,img.Width,img.Height,GraphicsUnit.Pixel);
   g.Dispose();
   //以下代码为保存图片时,设置压缩质量
   EncoderParameters encoderParams=new EncoderParameters();
   long[] quality=new long[1];
   quality[0]=100;
   EncoderParameter encoderParam= new EncoderParameter(System.Drawing.Imaging.Encoder.Quality,quality);
   encoderParams.Param[0]=encoderParam;
   //获取包含有关内置图像编码解码器的信息的ImageCodecInfo对象。
   ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
   ImageCodecInfo jpegICI=null;
   for(int x=0;x<arrayICI.Length;x++)
   {
    if(arrayICI[x].FormatDescription.Equals("JPEG"))
    {
     jpegICI=arrayICI[x];//设置jpeg编码
     break;
    }
   }
   if(jpegICI!=null)
   {
    outBmp.Save(newfile,jpegICI,encoderParams);
   }
   else
   {
    outBmp.Save(newfile,thisformat);
   }
   img.Dispose();
   outBmp.Dispose();
  }

posted @ 2009-03-06 12:54  perfectMan  阅读(939)  评论(0)    收藏  举报