WPF references images in the DLL pure image resource package class library, the wpf class library
1. The process of creating a WPF application is omitted. 2. Create a class library project (image resource package) create an image resource class library project MyImages, delete class1.cs, and select the "image" type in the resource option of the Project attribute, click "add existing file" in "Add Resource" to add the image to the resource. Change the access modifier to Public. 3. reference the class library project in the WPF Application to access the image through MyImages. Properties. Resources. XXX in WPF. XXX is the image file name (Resource Name ). However, you still need to work on images in WPF. 4. Create a Rectangle in WPF or other controls that use the ImageBrush object as the fill or background. Set the ImageSource attribute of ImageBrush to the image in the resource package as follows:
/// <Summary> /// read the symbol (file in the image repository) /// </summary> /// <param name = "symbolName"> </param> /// <returns> </returns> public static ImageBrush GetImagebrush (string ImageName) {ImageBrush imageBrush = new ImageBrush (); System. resources. resourceManager rm = ImageLibrary. properties. resources. resourceManager; System. drawing. bitmap B = (System. drawing. bitmap) rm. getObject (ImageName); imageBrush. imageSource = ToWpfBitmap (B); return imageBrush ;}
Public static BitmapSource ToWpfBitmap (Bitmap bitmap) {using (MemoryStream stream = new MemoryStream () {// note: the original format of the converted image is set to BMP, JPG, PNG, and other bitmap. save (stream, ImageFormat. png); stream. position = 0; BitmapImage result = new BitmapImage (); result. beginInit (); // According to MSDN, "The default OnDemand cache option retains access to the stream until the image is needed. "// Force the bitmap to load right now so we can dispose the stream. result. cacheOption = BitmapCacheOption. onLoad; result. streamSource = stream; result. endInit (); result. freeze (); return result ;}}
Call method: Rectangle1.Fill = GetImagebrush (ImageName); note that the original ImageFormat of the converted image must be set correctly. For example, if the original image is in PNG format, it will be distorted when it is called in BMP format.