2017-04-13 47 views
0

我正在编写使用文件路径从文件夹中读取图像的代码(.gif)并将它们存储在datagridObject中,以便稍后在dataGrid中显示它们。将位图资源读入Uri

的代码看起来是这样的:

string[] filePaths = Directory.GetFiles(Images_File); 
var L = new List<DataGridObject>(); 
for (int z = 0; z < list_Exp.Count; z++) 
     { 
      var d = new DataGridObject(); 

      d.MainName = list_MainName[z]; 
      d.Level = list_Level[z]; 
      d.Exp = list_Exp[z]; 

      d.ImageSource = new Uri(String.Format("{0}\\{1}.gif", Images_File, list_MainName[z]), UriKind.RelativeOrAbsolute); 

      L.Add(d); 

     } 

     dataGrid.ItemsSource = L; 

不过,我想使它成为一个.exe文件,将所有的图像文件作为资源。

我嵌入图像作为一种资源,我尝试使用:

d.ImageSource = new Bitmap(namespace.Properties.Resources.list_MainName[z]); 

但即时得到一个错误:

Cannot implicitly convert type System.Drawing,Bitmap to System.Uri

有没有一种很好的方式来使用for循环内的图像资源,并将它们存储到一个对象?

非常感谢。

回答

0

添加一个新的资源文件,然后根据需要添加图像到这个文件。 我们可以使用ResourceReader迭代图像。

public Dictionary<string,Bitmap> GetEmbeddedImages() 
{ 
    // Add a new Resources file named Resource1.resx; VS will generate a static class named Resource1 
    // Add images to this file as required 

    var assembly = System.Reflection.Assembly.GetExecutingAssembly(); 
    var resourceName = String.Format("{0}.{1}.resources", assembly.GetName().Name, typeof(Resource1).Name); 

    Dictionary<string, Bitmap> images = new Dictionary<string, Bitmap>(); 

    using (var rStream = assembly.GetManifestResourceStream(resourceName)) 
    using (var rReader = new ResourceReader(rStream)) 
    { 
     foreach (DictionaryEntry de in rReader) 
     { 
      var itemName = (string)de.Key; 
      var itemValue = (Bitmap)de.Value; 

      images.Add(itemName, itemValue); 
     } 
    } 

    return images; 
}