Welcome to OStack Knowledge Sharing 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...