In many cases, we use images to decorate the UI, for example, as the control background.
These images can be divided into two forms: Images in the local file system and images in the memory.
The two types of images are used differently in WPF. The following describes how to use these two types of images.
1. Image files in the local file system
This type of image is very easy to use. You can directly specify the path in xaml, for example:
1 <Button>
2 <Button. Background>
3 <ImageBrush ImageSource = "bg.jpg"/>
4 </Button. Background>
5 </Button>
The corresponding C # code is
1 ImageBrush imageBrush = new ImageBrush ();
2imageBrush. ImageSource = new BitmapImage (new Uri ("bg.jpg", UriKind. Relative ));
3button. Background = imageBrush;
The imageBrush. ImageSource type is ImageSource, while ImageSource is an abstract class,
Therefore, instead of using it directly, we can use its subclass instead. After reading MSDN, we can see their inheritance relationships:
System. Windows. Media. ImageSource
System. Windows. Media. DrawingImage
System. Windows. Media. Imaging. BitmapSource
2. Images in memory
For images that only exist in the memory, the above method seems powerless. We should look for another method. The following describes a method:
First look at the code:
1 // Here, the image is read from the file to simulate the image in memory.
2System. Drawing. Bitmap bitmap = new System. Drawing. Bitmap ("bg.jpg ");
3 MemoryStream stream = new MemoryStream ();
4bitmap. Save (stream, System. Drawing. Imaging. ImageFormat. Png );
5 ImageBrush imageBrush = new ImageBrush ();
6 ImageSourceConverter imageSourceConverter = new ImageSourceConverter ();
7
8imageBrush. ImageSource = (ImageSource) imageSourceConverter. ConvertFrom (stream );
9button. Background = imageBrush;
Here, bitmap is an image of the Bitmap type that exists in the memory. It is simulated by directly loading the local image file.
The step is to save it to the stream first, and then use the ConvertFrom method of the ImageSourceConverter class to get the image we need from the stream.
ImageSource usage