How to get a System.Drawing.Image object from image which build action is marked as Resource?

前端 未结 2 1272
醉话见心
醉话见心 2021-01-22 05:50

I have a wpf app,and got a image useful for codebehind which\'s location in the project is something like \"projectName\\images\\pp.png\" and its build action is \"Resource\"(No

相关标签:
2条回答
  • 2021-01-22 06:53

    Windows Forms - Get an image embedded resource:

    var assembly = System.Reflection.Assembly.GetExecutingAssembly();
    var stream= assembly.GetManifestResourceStream("YourAssemblyName.images.pp.png");
    var image = Image.FromStream(stream);
    

    Note:

    • "YourAssemblyName.images.pp.png" is case sensitive
    • Instead of YourAssemblyName put your assembly name, for example for my project, it is my project name and also my default namespace.
    • If you are not sure what exactly pass to GetManifestResourceStram use the code below:

    Find embedded resource names:

    var assembly = System.Reflection.Assembly.GetExecutingAssembly();
    assembly.GetManifestResourceNames()
            .Where(x => x.EndsWith("pp.png")) //Comment this line to find all resource names
            .ToList()
            .ForEach(resource =>
            {
                MessageBox.Show(resource);
            });
    
    0 讨论(0)
  • 2021-01-22 06:55

    WPF - Get an Image Resource and Convert to System.Drawing.Image

    var bitmapImage = new BitmapImage(new Uri(@"pack://application:,,,/"
        + Assembly.GetExecutingAssembly().GetName().Name
        + ";component/"
        + "images/pp.png", UriKind.Absolute));
    
    var encoder = new PngBitmapEncoder();
    encoder.Frames.Add(BitmapFrame.Create((BitmapImage)bitmapImage));
    var stream = new MemoryStream();
    encoder.Save(stream);
    stream.Flush();
    var image = new System.Drawing.Bitmap(stream);
    

    Note:

    • Use "/" instead of "\"
    • Consider reading Pack URIs in WPF (important part: Resource File Pack URIs)
    • Add reference to system.drawing.dll

    Local Assembly Resource File

    The pack URI for a resource file that is compiled into the local assembly uses the following authority and path: pack://application:,,,/ReferencedAssembly;component/Subfolder/ResourceFile.Ext

    0 讨论(0)
提交回复
热议问题