問題描述
我正在嘗試將我的位圖保存到 MemoryStream - 這段代碼有什么問題?為什么它讓我argumentnullexception ?
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: StackTrace System.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(" {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.
這篇關于參數空異常位圖保存到內存流的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!