本文介绍了参数nullexception位图保存到内存流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图将我的位图保存到MemoryStream-此代码有什么问题?为什么它让我争执nullexception ??

I'm trying to save my Bitmap to MemoryStream - what wrong in this code? Why it gets me argumentnullexception ??

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(位图条形码)中

UPD: StackTraceSystem.Drawing.Image.Save(Stream stream, ImageCodecInfo encoder, EncoderParameters encoderParams)in WordTest.FormTestWord.insertBarCodesToPDF(Bitmap barcode)

推荐答案

我相信您的问题与您要保存到MemoryStream的图像类型有关.根据此代码项目文章:动态生成图标(安全),其中有些是ImageFormat类型没有必要的编码器,无法将保存功能另存为该类型.

I believe that your problem is related to the type of image you are trying to save to the MemoryStream as. According to this Code Project article: Dynamically Generating Icons (safely), some of the ImageFormat types do not have the necessary encoder to allow the Save function to save as that type.

我运行以下命令来确定哪些类型起作用和不起作用:

I ran the following to determine which types did and didn't work:

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文章,其中指出了某些ImageFormat类型是只读的.

There is a Microsoft KB Article which states that some of the ImageFormat types are read-only.

这篇关于参数nullexception位图保存到内存流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 04:47