argumentnullexception位图保存到内存流

本文关键字:内存 保存 位图 argumentnullexception | 更新日期: 2023-09-27 18:21:13

我正试图将位图保存到MemoryStream-这段代码有什么问题?为什么它会让我争论nullexception??

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

UPD:StackTraceSystem.Drawing.Image.Save(流、ImageCodecInfo编码器、EncoderParameters编码器参数)在WordTest.FormTestWord.insertBarCodesToPDF(位图条形码)中

argumentnullexception位图保存到内存流

我相信你的问题与你试图保存到MemoryStream的图像类型有关。根据这篇代码项目文章:动态生成图标(安全),一些ImageFormat类型没有必要的编码器来允许save函数保存为该类型。

我运行以下程序来确定哪些类型有效和无效:

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知识库文章指出,某些ImageFormat类型是只读的。