日期:2014-05-17  浏览次数:20431 次

c#图片压缩问题
在网上找了一段压缩图片的代码如下:
  public void ystp(string filePath, string filePath_ystp) //压缩图片
  {
  //Bitmap
  Bitmap bmp = null;  
  //ImageCoderInfo 
  ImageCodecInfo ici = null;
  //Encoder
  Encoder ecd = null;
  //EncoderParameter
  EncoderParameter ept = null;
  //EncoderParameters
  EncoderParameters eptS = null;
  try
  {
  bmp = new Bitmap(filePath);
  ici = this.getImageCoderInfo("image/jpeg");
  ecd = Encoder.Quality;
  eptS = new EncoderParameters(1);
  ept = new EncoderParameter(ecd, 10L);
  eptS.Param[0] = ept;
  bmp.Save(filePath_ystp, ici, eptS);
  }
  catch (Exception ex)
  {
  throw new Exception(ex.Message);
  }
  finally
  {
  bmp.Dispose();
  ept.Dispose();
  eptS.Dispose();
  }
  }
  private ImageCodecInfo getImageCoderInfo(string coderType)// 获取图片编码类型信息
  {
  ImageCodecInfo[] iciS = ImageCodecInfo.GetImageEncoders();

  ImageCodecInfo retIci = null;

  foreach (ImageCodecInfo ici in iciS)
  {
  if (ici.MimeType.Equals(coderType))
  retIci = ici;
  }

  return retIci;
  }

虽然压缩之后效果上有点差,不过勉强能用,不过更让人压抑的是,在本地通过,传到服务器之后确报错说什么System.NullReferenceException: 未将对象引用设置到对象的实例。定位在这句bmp.Dispose();这个明明是实例华了,为什么会没有呢?的却上传图片花了几秒中时间,难道是因为这几秒,这个对象自己已经释放了,可是这张图片没有上传成功啊,不知道是怎么回事,请各位帮忙,谢!


------解决方案--------------------
写成 Bitmap bmp = new Bitmap(filePath); 

就好了, 我也不明白 为什么,但是只能这么做 

C# code
Bitmap bmp = new Bitmap(filePath); 

//ImageCoderInfo 
ImageCodecInfo ici = null; 
//Encoder 
Encoder ecd = null; 
//EncoderParameter 
EncoderParameter ept = null; 
//EncoderParameters 
EncoderParameters eptS = null; 
try 

ici = this.getImageCoderInfo("image/jpeg"); 
ecd = Encoder.Quality; 
eptS = new EncoderParameters(1); 
ept = new EncoderParameter(ecd, 10L); 
eptS.Param[0] = ept; 
bmp.Save(filePath_ystp, ici, eptS); 




------解决方案--------------------
图片的路径不对吧
------解决方案--------------------
bmp = new Bitmap(filePath); 
这段代码,如果在本地计算机调试,这里的filePath应该是你本地硬盘上的路径。

如果这段代码运行在服务器上,那么如果filePath是c:\\1.gif,那么应该确保在服务器上的c盘下存在1.gif,而不是开发计算机上。

==================

try 

bmp = new Bitmap(filePath);

catch (Exception ex) 

throw new Exception(ex.Message); 

finally 

bmp.Dispose(); 
ept.Dispose(); 
eptS.Dispose(); 

假设bmp = new Bitmap(filePath); 这里的filePath不存在,那么肯定会运行到throw new这一行,接着运行 finally下面的bmp.dispose,而这里因为出现