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

前端 未结 2 1277
醉话见心
醉话见心 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: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

提交回复
热议问题