How to convert a drawing image to the source of a WPF control

Source: Internet
Author: User

This example takes canvas as an example

<Canvas>
<image stretch= "Fill" width= "" "" height= "x:name=" MyImage "/>
</Canvas>

One way:
System.Drawing.Image bmp= ...; A valid image that is initialized by itself
System.IO.MemoryStream ms = new System.IO.MemoryStream ();
Bmp. Save (MS, SYSTEM.DRAWING.IMAGING.IMAGEFORMAT.BMP);//format self-processing, here with bitmap
downlink, initial a imagesource as source of MyImage
System.Windows.Media.Imaging.BitmapImage bi=new System.Windows.Media.Imaging.BitmapImage ();
Bi. BeginInit ();
Bi. Streamsource = new MemoryStream (Ms. ToArray ()); Do not use MS directly
Bi. EndInit ();
Myimage.source = bi; done!
Ms. Close ();

Another method (the more common method):
System.Drawing.Image bmp= ...; A valid image that is initialized by itself
System.Windows.Media.Imaging.BitmapSource bi =
System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap (
Bmp. Gethbitmap (),
IntPtr.Zero,
Int32rect.empty,
Bitmapsizeoptions.fromemptyoptions ());
Above in BMP format for example, other format self-processing
Myimage.source = bi; done!

Refer to the following methods of System.Windows.Interop.Imaging:
Createbitmapsourcefromhbitmap ()//Get ImageSource from Hbitmap
Createbitmapsourcefromhicon ()//Get ImageSource from Hicon
Createbitmapsourcefrommemorysection ()//Get ImageSource from Hmem

The following are additional examples of code snippets in the following work:

Captureimagetool capture = new Captureimagetool ();
if (capture. ShowDialog () = = System.Windows.Forms.DialogResult.OK)
{
System.Drawing.Image Image = Capture. Image; Get drawing image
Bitmap bmp = new Bitmap (image); Get bitmap
System.Windows.Media.Imaging.BitmapSource Bmpresource =
System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap (BMP. Gethbitmap (),
IntPtr.Zero,
Int32rect.empty,
Bitmapsizeoptions.fromemptyoptions ()); to bitmap resource
Image1.               Source = Bmpresource; Done
}

How to convert a drawing image to the source of a WPF control

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.