一个实用的操作客户上传图片的函数(C#)


一个可以使得上传的图片大小按照指定的宽度,高度自动按比例进行缩放,还可以指定生成图片质量的压缩比

,生成的JPG还可以指定其图片的压缩比。很实用。

 
  private ImageCodecInfo myImageCodecInfo;
  private EncoderParameter myEncoderParameter;
  private EncoderParameters myEncoderParameters;
  public Bitmap b;
  private Graphics g;


public string upimgscalesave(HttpPostedFile UpFile,string id,int imgw,string bcwz)

//UpFile HtmlInputFile控件类

//id 上传后保存的文件名

//改变的图片宽度,高度吗,当然是自动计算拉!

//bcwz上传后要存服务器那里啊!
  {
        int FileLength;
        int imgh=0;
        FileLength = UpFile.ContentLength; //记录文件长度
 
               if (FileLength == 0)
              { //文件长度为零时
                          return "null";
               }
              else
                {
                 Byte[] FileByteArray = new Byte[FileLength]; //图象文件临时储存Byte数组 
                 Stream StreamObject = UpFile.InputStream; //建立数据流对像
                 StreamObject.Read(FileByteArray,0,FileLength); 
                 System.Drawing.Image orimg=System.Drawing.Image.FromStream(StreamObject);
    
    
                  string mimeType ="image/jpeg";
                  ImageCodecInfo[] encoders;
                  encoders = ImageCodecInfo.GetImageEncoders();
                  for(int j = 0; j < encoders.Length; ++j)
                  {
                     if(encoders[j].MimeType == mimeType)
                     myImageCodecInfo=encoders[j];
                  }


                   System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
                   myEncoderParameters = new EncoderParameters(1);
                   myEncoderParameter = new EncoderParameter(myEncoder, 80L);

                  //80L压缩比拉
                   myEncoderParameters.Param[0] = myEncoderParameter;
    
    
               if(imgw==0)    //宽度为0时,就原大小上传
         { 
     
     
     
                orimg.Save(bcwz+"\\"+id+".jpg",myImageCodecInfo,myEncoderParameters);   
                orimg.Dispose();
     
              }
             else
            {
                double bl=0.0F;
                 bl=imgw/Convert.ToDouble(orimg.Width);
                 imgh=Convert.ToInt32(orimg.Height*bl);
                  b = new Bitmap(imgw,imgh);
                   g = Graphics.FromImage(b);  
                 Rectangle destRect1 = new Rectangle( 0, 0, imgw, imgh);
                g.DrawImage(orimg,destRect1);
                 b.Save(bcwz+"\\"+id+".jpg",myImageCodecInfo,myEncoderParameters);
                  b.Dispose();
                 g.Dispose();
                orimg.Dispose();

               }
              return bcwz;
 //返回图片保存位置
           }
  }
写的比较乱!!

posted on 2004-09-01 11:26  茄子  阅读(199)  评论(0)    收藏  举报

导航