I have file animaha135.gif in /Images folder, set "Build Action" as "Embedded Resource" or "Resources", I want to get this image to bitmap:
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'.
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:
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):
//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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.