1. Build WPF application process slightly. 2. Create a Class library project (Picture resource bundle) Create a Picture Resource Class Library project MyImages, delete Class1.cs, select the "image" type in the resource options for the project properties, and in "Add Resources", click "Add Existing File" to add the image to the resource. and change the access modifier to public. 3. Referencing a class library project in a WPF application can access the image through MyImages.Properties.Resources.XXX in WPF. XXX is the image file name (resource name). But in WPF, it takes a bit of work to get to the image. 4. In WPF, create rectangle or other controls that take a ImageBrush object as a fill or background, and set the ImageSource property of ImageBrush to the image in the resource bundle as follows:
/// <summary> ///reading symbols (files in the picture library)/// </summary> /// <param name= "Symbolname" ></param> /// <returns></returns> Public StaticImageBrush Getimagebrush (stringImageName) {ImageBrush ImageBrush=NewImageBrush (); System.Resources.ResourceManager RM=ImageLibrary.Properties.Resources.ResourceManager; System.Drawing.Bitmap b=(SYSTEM.DRAWING.BITMAP) rm. GetObject (ImageName); Imagebrush.imagesource=Towpfbitmap (b); returnImageBrush; }
Public StaticBitmapSource Towpfbitmap (Bitmap Bitmap) {using(MemoryStream stream =NewMemoryStream ()) { //Note: The original format of the converted picture ImageFormat set to BMP, JPG, PNG, etc.bitmap. Save (stream, imageformat.png); Stream. Position=0; BitmapImage result=NewBitmapImage (); Result. BeginInit (); //according to MSDN, "The default OnDemand caches 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 (); returnresult; } }
Call method: Rectangle1.fill=getimagebrush (ImageName); Note the original format of the converted picture ImageFormat must be set correctly. If the original image is in PNG format, the call will be distorted when it is set to BMP format.
WPF reference DLL images in a pure Image Resource Pack class library