WPF / WinForms / GDI互操作:将WriteableBitmap转换为System.Drawing.Image?

时间:2010-07-13 16:53:18

标签: c# wpf winforms writeablebitmap winforms-interop

如何将WPF WriteableBitmap对象转换为System.Drawing.Image?

我的WPF客户端应用程序将位图数据发送到Web服务,Web服务需要在此端构建System.Drawing.Image。

我知道我可以获取WriteableBitmap的数据,将信息发送到Web服务:

// WPF side:

WriteableBitmap bitmap = ...;
int width = bitmap.PixelWidth;
int height = bitmap.PixelHeight;
int[] pixels = bitmap.Pixels;

myWebService.CreateBitmap(width, height, pixels);

但是在Web服务端,我不知道如何根据这些数据创建System.Drawing.Image。

// Web service side:

public void CreateBitmap(int[] wpfBitmapPixels, int width, int height)
{
   System.Drawing.Bitmap bitmap = ? // How can I create this?
}

3 个答案:

答案 0 :(得分:3)

此博客post展示了如何将WriteableBitmap编码为jpeg图像。也许这有帮助吗?

如果你真的想传输原始图像数据(像素),你可以:

  1. 创建一个大小正确的System.Drawing.Bitmap
  2. 迭代原始数据,将原始数据转换为System.Drawing.Color(例如通过Color.FromArgb(),并通过SetPixel()
  3. 设置新创建的图像中的每个像素颜色

    我绝对更喜欢第一个解决方案(博客文章中描述的解决方案)。

答案 1 :(得分:3)

如果您的位图数据未压缩,则可以使用此System.Drawing.Bitmap构造函数:Bitmap(Int32, Int32, Int32, PixelFormat, IntPtr)

如果位图编码为jpg或png,请从位图数据创建MemoryStream,并将其与Bitmap(Stream)构造函数一起使用。

编辑:

由于您要将位图发送到Web服务,我建议您先对其进行编码。 System.Windows.Media.Imaging命名空间中有几个编码器。例如:

    WriteableBitmap bitmap = ...;
    var stream = new MemoryStream();               
    var encoder = new JpegBitmapEncoder(); 
    encoder.Frames.Add( BitmapFrame.Create( bitmap ) ); 
    encoder.Save( stream ); 
    byte[] buffer = stream.GetBuffer(); 
    // Send the buffer to the web service   

在接收端,只需:

    var bitmap = new System.Drawing.Bitmap( new MemoryStream( buffer ) );

希望有所帮助。

答案 2 :(得分:0)

问题出在WPF上,Pixels似乎不是WriteableBitmap的属性。这里的一些答案指向SilverLight的文章,所以我怀疑这可能是WPF和SilverLight之间的区别。

相关问题