Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

c# - argumentnullexception bitmap save to memorystream

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: StackTrace System.Drawing.Image.Save(Stream stream, ImageCodecInfo encoder, EncoderParameters encoderParams) in WordTest.FormTestWord.insertBarCodesToPDF(Bitmap barcode)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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("{0}", (success ? "works" : "fails"));
}

This gave the results of:

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...