上节讲了在Silverlight中如何由image生成bytes,如果把bytes信息传给WPF应用,那么如何生成image呢
众所周知,Silverlight和WPF的库是不同的,所以不能像上节那样直接转换回去。
首先,根据bytes信息以及像素宽度和高度生成Bitmap。
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
public static System.Drawing.Bitmap BitsToBitmapRGB32(Byte[] bytes, int width, int height) { System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); int i; System.Drawing.Imaging.BitmapData data = bmp.LockBits(new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, bmp.PixelFormat); if (data.Stride == width * 4) { Marshal.Copy(bytes, 0, data.Scan0, width * height * 4); } else { for (i = 0; i < bmp.Height; i++) { IntPtr p = new IntPtr(data.Scan0.ToInt32() + data.Stride * i); Marshal.Copy(bytes, i * bmp.Width * 4, p, bmp.Width * 4); } } bmp.UnlockBits(data); return bmp; }
之后,把Bitmap转成BitmapSource。
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
static System.Windows.Media.Imaging.BitmapSource ConvertBitmapToBitmapSource(System.Drawing.Bitmap bitmap) { IntPtr hBitmap = bitmap.GetHbitmap(); return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( hBitmap, IntPtr.Zero, Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions()); }
最后,根据BitmapSource生成Image控件。
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
var realImage = new System.Windows.Controls.Image() { Source = ConvertBitmapToBitmapSource(bitmap), Stretch = Stretch.None };