The previous section describes how to generate an image if bytes are generated by an image in Silverlight. If bytes information is transmitted to the WPF application, how can we generate an image?
As we all know, Silverlight and WPF libraries are different, so they cannot be converted back directly as in the previous section.
First, bitmap is generated based on bytes information, pixel width, and height.
View code
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 ;}
Then, convert bitmap to bitmapsource.
View code
StaticSystem. Windows. Media. imaging. bitmapsource convertbitmaptobitmapsource (system. Drawing. Bitmap bitmap) {intptr hbitmap=Bitmap. gethbitmap ();ReturnSystem. Windows. InterOP. imaging. createbitmapsourcefromhbitmap (hbitmap, intptr. Zero, int32rect. Empty, system. Windows. Media. imaging. bitmapsizeoptions. fromemptyoptions ());}
Finally, the image control is generated based on bitmapsource.
View code
var realimage = New system. windows. controls. image () {source = convertbitmaptobitmapsource (Bitmap), stretch = stretch. none};