Set a ImageSource from FileSystem in Metro app
-
11-12-2019 - |
Question
In the ApplicationData.Current.RomanigFolder, I save an jpg file. It is possible to read the content of this file in a stream or MemoryStream and set it to the ImageSource?
I use it in a WPF-Application with .NET 4.0 with follwing code: (img is a XAML-Image-Control
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.CacheOption = BitmapCacheOption.OnLoad;
StreamReader sr = new StreamReader(data.message.imageUrl);
bi.StreamSource = sr.BaseStream;
bi.EndInit();
img.Source = bi;
sr.Close();
For a Metro app I see no way to set a StreamSource to an BitmapImage. How can I set a Image-File to an Image-Control?
Solution
For writing “Metro Style Apps”, or apps built for Windows 8, to set the source of an image in WPF project.
Here’s the code:
// Usage
myImage.Source = ImageFromRelativePath(this, "relative_path_to_file_make_sure_build_set_to_content");
public static BitmapImage ImageFromRelativePath(FrameworkElement parent, string path)
{
var uri = new Uri(parent.BaseUri, path);
BitmapImage result = new BitmapImage();
result.UriSource = uri;
return result;
}
Reference: http://www.codingbeta.com/programatically-setting-image-source-in-metro-style-apps-with-wpf/
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow