2011-12-16 6 views
1

問題:是否有從字符串文本(參數,即文件名和路徑)和提供給圖像類型的文件信息的C#.NET內置轉換?

你知道在.NET中,可以轉換我的文字(字符串)東西,並返回圖像類型?像.Net「轉換」類,但它不支持圖像轉換。 我的意思是......就像傳遞文件信息(文件名和路徑)作爲參數並返回圖像(位圖)來顯示。 我真的必須手動編碼嗎?

場景:

成功採集圖像文件的一些列出目錄中(從閃存驅動器或本地驅動器),並希望顯示這些作爲一個實際的圖像。

希望我的問題清楚。

回答

0

取決於是否您正在使用的WinForms或WPF,你可以使用System.Drawing.ImageSystem.Windows.Media.ImageSource

您無法將字符串轉換爲屏幕上的圖像。您必須將其加載到另一個組件中。例如,Image有一個靜態的FromFile(string filepath)方法,用於加載圖像並使其可用於顯示。

0

實現IValueConverter接口,並返回位圖。

public class MyValueConverter : IValueConverter {   

/* 
Implement this method to modify the source data before sending it to display 
*/ 
     public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)  { 
      try   { 
       return new BitmapImage(new Uri("../Images/" + (string)(value), UriKind.Relative)); 
      } 
      catch{ 
       return new BitmapImage(); 
      } 
     } 
/* 
Implement this method to modify the target data before sending it back to the source. 
*/ 

     public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)  { 
      var img = value as BitmapImage; 
      return img.UriSource.AbsoluteUri; 
     } 

    } 
+0

這不是冒險有關的內存消耗? – Minustar 2011-12-16 07:04:53

+0

我還沒有給出這個想法,但我的主要目標是它可以在WPF,Silverlight,WP7 ... – 2011-12-16 07:20:28

0

您可以使用Bitmap.FromFile("FileName")或者你可以使用Image.FromFile("FileName")。如果你想要得到位圖的數組,你可以使用一個簡單的LINQ查詢

var fileNames = new string[] { "file1", "file2", "file3" }; 
var myImages = fileNames.Select(x => Bitmap.FromFile(x)).ToArray(); 
相關問題