简体   繁体   English

WPF - 无法获取资源文件

[英]WPF - can't get resource file

I have file animaha135.gif in /Images folder, set "Build Action" as "Embedded Resource" or "Resources", I want to get this image to bitmap: 我在/ Images文件夹中存档animaha135.gif,将“Build Action”设置为“Embedded Resource”或“Resources”,我想将此图像转换为位图:

            var image = new BitmapImage();
            image.BeginInit();
            image.UriSource = new Uri("pack://application:,,,/Images/animaha135.gif");
            image.EndInit();

but it does not work: 但它不起作用:

Cannot locate resource 'images/animaha135.gif'. 找不到资源'images / animaha135.gif'。

what I do incorrectly? 我做错了什么?


solved this problem. 解决了这个问题。 Name of assembly was another than name of project. 程序集的名称不是项目名称。 I set the same and my first code works 我设置相同,我的第一个代码工作

Don t build as "Embedded Resource". 不要建立“嵌入式资源”。 Build as "Resource". 构建为“资源”。 -> worked for me - >为我工作

EDIT: 编辑:

use this to create your uri: 用它来创建你的uri:

protected static Uri GetUri(string filename, Type type)
{
    Assembly assembly = type.Assembly;
    string assemblyName = assembly.ToString().Split(',')[0];
    string uriString = String.Format("pack://application:,,,/{0};component/{1}",
        assemblyName, filename);
    return new Uri(uriString);
}

I used this for custom shadereffects 我用它来定制阴影效果

If you use embeed resources, you need read assembly maniffest 如果您使用嵌入资源,则需要阅读程序集

      private void LoadImg()
    {

       //x is name of <Image name="x"/>
       x.Source = GetResourceTextFile(GetResourcePath("Images/animaha135.gif"));


    }


    private string GetResourcePath(string path)
    {
        return path.Replace("/", ".");
    }


    public BitmapFrame GetResourceTextFile(string filename)
    {

        string result = string.Empty;

        using (Stream stream = this.GetType().Assembly.GetManifestResourceStream(String.Format("{0}.{1}",this.GetType().Assembly.GetName().Name,filename)))
        {
            BitmapFrame bmp = BitmapFrame.Create(stream);
            return bmp;
        }

    }

Other solution (return Bitmap): 其他解决方案(返回Bitmap):

 //Use   BitmapImage bitmap = GetResourceTextFile(GetResourcePath("Images/animaha135.gif"));


    public BitmapImage GetResourceTextFile(string filename)
    {

        string result = string.Empty;

        using (Stream stream = this.GetType().Assembly.GetManifestResourceStream(String.Format("{0}.{1}",this.GetType().Assembly.GetName().Name,filename)))
        {

            BitmapImage bi = new BitmapImage();
            bi.BeginInit();
            bi.StreamSource = stream;
            bi.EndInit();

            return bi;
        }

    }

Note: Embed resources replace path => / by . 注意:嵌入资源替换path => / by。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM