Silverlight tips [4]: How to convert bytes to image in WPF

Source: Internet
Author: User

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}; 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.