argumentnullexception位图保存到memorystream

时间:2014-09-10 01:04:33

标签: c# bitmap save memorystream

我正在尝试将我的Bitmap保存到MemoryStream - 这段代码有什么问题?为什么它让我争论?

private void insertBarCodesToPDF(Bitmap barcode)
    {

            .......
            MemoryStream ms = new MemoryStream();
            barcode.Save(ms, System.Drawing.Imaging.ImageFormat.MemoryBmp); //<----
            byte [] qwe = ms.ToArray();
            .......

    }

UPD: StackTrace System.Drawing.Image.Save(Stream stream,ImageCodecInfo encoder,EncoderParameters encoderParams) 在WordTest.FormTestWord.insertBarCodesToPDF(位图条形码)

1 个答案:

答案 0 :(得分:9)

我认为您的问题与您尝试保存到MemoryStream的图像类型有关。根据此代码项目文章:Dynamically Generating Icons (safely),某些ImageFormat类型没有必要的编码器来允许保存功能保存为该类型。

我运行以下内容以确定哪些类型有效,哪些无效:

System.Drawing.Bitmap b = new Bitmap(10, 10);
foreach (ImageFormat format in new ImageFormat[]{
          ImageFormat.Bmp, 
          ImageFormat.Emf, 
          ImageFormat.Exif, 
          ImageFormat.Gif, 
          ImageFormat.Icon, 
          ImageFormat.Jpeg, 
          ImageFormat.MemoryBmp,
          ImageFormat.Png,
          ImageFormat.Tiff, 
          ImageFormat.Wmf}) 
{
  Console.Write("Trying {0}:", format);
  MemoryStream ms = new MemoryStream();
  bool success = true;
  try 
  {
    b.Save(ms, format);
  }
  catch (Exception) 
  {
    success = false;
  }
  Console.WriteLine("\t{0}", (success ? "works" : "fails"));
}

这给出了结果:

Trying Bmp:       works
Trying Emf:       fails
Trying Exif:      fails
Trying Gif:       works
Trying Icon:      fails
Trying Jpeg:      works
Trying MemoryBMP: fails
Trying Png:       works
Trying Tiff:      works
Trying Wmf:       fails

Microsoft KB Article表示某些ImageFormat类型是只读的。