原始位图数据到图像控件

时间:2013-09-19 20:53:19

标签: c# .net wpf bitmap c++-cli

我的c#WPF应用程序DisplayFile中有一个函数,用于使用位图图像填充System.Windows.Controls.Image。此位图图像是从fileName:

提供的文件加载的
public void DisplayFile(System.Windows.Controls.Image imageBox, TextBlock textBox, 
                        String fileName)
    {      
        Bitmap bmp;
        BitmapImage bitmapImage;
        StringBuilder strBldr = new StringBuilder(_ObjFolderPath);
        strBldr.Append(fileName);

        ExtractBitmapAndDescriptor(strBldr.ToString(), out newtext, out bmp);

        using (MemoryStream memory = new MemoryStream())
        {
            bmp.Save(memory, ImageFormat.Bmp);
            memory.Position = 0;
            bitmapImage = new BitmapImage();
            bitmapImage.BeginInit();
            bitmapImage.StreamSource = memory;
            bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
            bitmapImage.EndInit();
        }

        imageBox.Source = bitmapImage;
        textBox.Text = newtext;

    }

ExtractBitmapAndDescriptor是一个用C ++ / CLI库编写的函数,用于读取给定文件并将Bitmap对象吐出回c#函数:

void ExtractBitmapAndDescriptor(String ^filePath,[Out] String ^%descriptor,[Out] Bitmap^% bmpIn)
{
    //... Seek through file until Bitmap information reached (File 
        // has an embedded bitmap file     
        //inside with no color pallette and was created using a c++ application)

            // reached bitmap Data
            BITMAPFILEHEADER bfh;
            BITMAPINFO bi;
            fread(&bfh, sizeof(BITMAPFILEHEADER), 1, in);
            fread(&bi, sizeof(BITMAPINFO)- sizeof(tagRGBQUAD), 1, in);

            BYTE* imageData = (BYTE*) malloc(   bi.bmiHeader.biSizeImage );

            ZeroMemory(imageData, bi.bmiHeader.biSizeImage);
            fread(imageData, bi.bmiHeader.biSizeImage,1, in);               


            bmpIn = gcnew Bitmap((int)bi.bmiHeader.biWidth, (int)bi.bmiHeader.biHeight, (int)bi.bmiHeader.biWidth*3, PixelFormat::Format24bppRgb,IntPtr( ( void * ) imageData ));

            System::Drawing::Rectangle newRect(0,0,bi.bmiHeader.biWidth, bi.bmiHeader.biHeight);
            bmpIn->LockBits(newRect, Imaging::ImageLockMode::ReadOnly,PixelFormat::Format24bppRgb);

    // Parse Other Data and return
}

代码给出了一个例外                    bmp.Save(memory,ImageFormat.Bmp); (DisplayFile函数)

的内容如下:

  

System.Drawing.dll中出现未处理的“System.Rutime.InteropServices.ExternalException”类型异常

     

GDI +中发生了一般性错误。

我注意到bmp中的rawdata成员(非公共成员)为null。我怀疑这是因为传入位图的原始数据最初是非托管数据上的托管指针而消失了。我认为LockBits应该确保它不会移动。

0 个答案:

没有答案