Why are my BitmapImages not displaying? - c#

Ad[a,o]pting Brundritt's example here, which he referenced in responding to my earlier BingMaps question, I have been able to display certain data in an "infobox" like so:
...but am not getting the BitmapImage that is part of the data I intend to display.
My question is why are the images not displaying, and what do I need to go in order to display them?
It's not the data - I've saved the thumbnail image to a SQLite database, where it is stored as an array of bytes, but which can be seen as images in SQLiteToolbox:
:
So as you can see, the String data is displaying fine, but not the image. Here is the pertinent code I've got for retrieving the data and displaying it:
// The class used to create the SQLite table
public class PhotraxBaseData
{
[SQLite.PrimaryKey]
[SQLite.AutoIncrement]
public int Id { get; set; }
. . .
public DateTime dateTimeTaken { get; set; }
public String filePath { get; set; }
public Byte[] thumbnail { get; set; }
}
private async void Gener8MapMarkers(List<PhotraxBaseData> _pbd)
{
foreach (PhotraxBaseData pbd in _pbd)
{
String descAndFilename = Path.GetFileName(pbd.filePath);
if (null != pbd.imgDescription)
{
descAndFilename = String.Format("{0} - {1}", pbd.imgDescription, descAndFilename);
}
BitmapImage bmi = await PhotraxUtils.ByteArrayToBitmapImage(pbd.thumbnail);
if (PhotraxUtils.ValidLatAndLong(pbd.latitude, pbd.longitude))
{
Location loc = new Location(pbd.latitude, pbd.longitude);
AddPushpin(loc, descAndFilename, pbd.dateTimeTaken, null, DataLayer);
}
}
}
public static async Task<BitmapImage> ByteArrayToBitmapImage(this byte[] byteArray)
{
// from http://dotnetspeak.com/2013/04/convert-byte-array-to-an-image-in-winrt
if (byteArray != null)
{
using (var stream = new InMemoryRandomAccessStream())
{
await stream.WriteAsync(byteArray.AsBuffer());
var image = new BitmapImage();
stream.Seek(0);
image.SetSource(stream);
return image;
}
}
return null;
}
public class PushpinMetadata
{
public string DescAndFileName { get; set; }
public DateTime DateTimeTaken { get; set; }
public BitmapImage Thumbnail { get; set; }
}
public void AddPushpin(Location latlong, string descAndFileName, DateTime dateTimeTaken, BitmapImage thumbnail, MapLayer layer)
{
Pushpin p = new Pushpin()
{
Tag = new PushpinMetadata()
{
DescAndFileName = descAndFileName,
DateTimeTaken = dateTimeTaken,
Thumbnail = thumbnail
}
};
MapLayer.SetPosition(p, latlong);
p.Tapped += PinTapped;
layer.Children.Add(p);
}
private void PinTapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e)
{
Pushpin p = sender as Pushpin;
PushpinMetadata m = (PushpinMetadata)p.Tag;
//Ensure there is content to be displayed
if (!String.IsNullOrEmpty(m.DescAndFileName))
{
Infobox.DataContext = m;
Infobox.Visibility = Visibility.Visible;
MapLayer.SetPosition(Infobox, MapLayer.GetPosition(p));
}
else
{
Infobox.Visibility = Visibility.Collapsed;
}
}
The XAML:
<bm:Map.Children>
<!-- Data Layer-->
<bm:MapLayer Name="DataLayer"/>
<!--Common Infobox-->
<bm:MapLayer>
<Grid x:Name="Infobox" Visibility="Collapsed" Margin="0,-115,-15,0">
<Border Width="300" Height="110" Background="Black" Opacity="0.8" BorderBrush="White" BorderThickness="2" CornerRadius="5"/>
<StackPanel Height="100" Margin="5">
<Grid Height="40">
<TextBlock Text="{Binding DescAndFileName}" FontSize="20" Width="250" TextWrapping="Wrap" HorizontalAlignment="Left" />
<Button Content="X" Tapped="CloseInfobox_Tapped" HorizontalAlignment="Right" VerticalAlignment="Top"/>
</Grid>
<Grid Height="40">
<Viewbox Height="200" Stretch="Uniform" StretchDirection="Both">
<Image Source="{Binding Thumbnail}" Width="Auto" Height="Auto" Margin="2"/>
</Viewbox>
</Grid>
<Grid Height="40">
<TextBlock Text="{Binding DateTimeTaken}" FontSize="16" Width="290" TextWrapping="Wrap" Height="Auto"/>
</Grid>
</StackPanel>
</Grid>
</bm:MapLayer>
<callisto:CustomDialog Content="CustomDialog" Height="100" Width="100"/>
</bm:Map.Children>
My guess is that the Image's Source property doesn't quite know what to do with the BitmapImage it's bound to via "Thumbnail"; but I don't know how to unbabelize the mismatch (presuming that's where the problem lies).
UPDATE
To answer Faye's brother Chris, here is the "database" (SQLite class) declaration:
public Byte[] thumbnail { get; set; }
Here is where I was calling the converter method, passing the appropriate member of the class instance, and then adding a pushpin:
BitmapImage bmi = await PhotraxUtils.ByteArrayToBitmapImage(pbd.thumbnail);
if (PhotraxUtils.ValidLatAndLong(pbd.latitude, pbd.longitude))
{
Location loc = new Location(pbd.latitude, pbd.longitude);
//AddPushpin(loc, descAndFilename, pbd.dateTimeTaken, null, DataLayer);
AddPushpin(loc, descAndFilename, pbd.dateTimeTaken, bmi, DataLayer);
}
However: MY BAD, PEOPLES!!!
I had neglected to replace my placeholder "null" arg with "bmi" (you can see my previous code commented out above, and my new working call to AddPushpin() below it). The image's size/scale is all wrong, but that can be fixed easily enough, I reckon.
I don't know whether to jump for joy or kick myself in the keister, so I think I'll do both simultaneously.
Thanks to Mr. Dunaway for making me look closer at my code - something I obviously should have done before posting.

Related

WPF: How to upload an image to your project and use it later on as a resource

I'm studying WPF at school but I ran into a problem with uploading a new image to my project.
The goal is to be able to add an image (at runtime) using a file browser. This image should be uploaded into the project and the filename should be saved in a database. Than it should be accessible as a resource in the project so I can show the image in a listbox for example.
This is what I've got so far:
View where the upload happens:
<Image Height="70px" Source="{Binding newImg}"/>
<Button Height="23" Name="btnLoad" VerticalAlignment="Bottom"
Width="75" Grid.Column="0" Grid.Row="1" Command="{Binding ImgUploadCommand}">_Browse</Button>
ViewModel UploadView
private string fullPath;
private BitmapImage image;
private Patient newPatient = new Patient();
private void KoppelenCommands()
{
FotoUploadCommand = new BaseCommand(FotoPatientUpload);
PatientOpslaanCommand = new BaseCommand(PatientOpslaan);
}
public ICommand FotoUploadCommand { get; set; }
public ICommand PatientOpslaanCommand { get; set; }
public void FotoPatientUpload()
{
OpenFileDialog op = new OpenFileDialog();
op.Title = "Select a picture";
op.Filter = "All supported graphics|*.jpg;*.jpeg;*.png|" +
"JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg|" +
"Portable Network Graphic (*.png)|*.png";
if (op.ShowDialog() == true)
{
image= new BitmapImage(new Uri(op.FileName));
fullPath = op.FileName;
string[] partsFileName = fullPath.Split('\\');
System.Windows.MessageBox.Show(delenFileName[(partsFileName.Length - 1)]);
NewPatient.Image= partsFileName[(delenFileName.Length - 1)];
}
}
public void PatientOpslaan()
{
string destinationPath = GetDestinationPath(NewPatient.Afbeelding, "\\assets\\images");
File.Copy(fullPath, destinationPath, true);
//dataservice (My DS works fine, I can see the correct filename in the database but I save only the name not the Path)
PatientDataService patientDS =
new PatientDataService();
patientDS.InsertPatient(NewPatient);
}
else
{
MessageBox.Show("Niet alle velden zijn ingevuld! Een nieuwe patient moet tenminste een naam en een voornaam krijgen!", "Fout!", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
//opslaan foto in opgegeven map <<Code afkomstig van stackoverflow auteur: Yashpal Singla>>
private static String GetDestinationPath(string filename, string foldername)
{
String appStartPath = System.IO.Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
appStartPath = String.Format(appStartPath + "\\{0}\\" + filename, foldername);
return appStartPath;
}
The image is correctly saved to the bin/debug/assets/images folder but not as a resource. Because it isn't saved as a resource I can't use it in my MainWindow View which looks like this:
<ListBox HorizontalContentAlignment="Center" ItemsSource="{Binding Patienten}" SelectedItem="{Binding SelectedPatient}" Grid.Column="0" Grid.Row="0">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<TextBlock Name="ImageNameListBox" Visibility="Collapsed"
Text="{Binding Image, StringFormat=../assets/images/{0}}" />
<Border Style="{StaticResource imageBorderStyle}" Grid.Column="0" Grid.Row="0" Height="80px" Width="80px">
<Rectangle Margin="1,-2,-2,1" Height="80px" Width="80px">
<Rectangle.Fill>
<ImageBrush ImageSource="{Binding Text, ElementName=ImageNameListBox}"/>
</Rectangle.Fill>
</Rectangle>
</Border>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
MainWindow ViewModel:
class MainWindowViewModel : BaseViewModel
{
private DialogService dialogService;
private ObservableCollection<Patient> patienten;
public ObservableCollection<Patient> Patienten
{
get
{
return patienten;
}
set
{
patienten = value;
NotifyPropertyChanged();
}
}
private Patient selectedPatient;
public Patient SelectedPatient {get; set;}
public MainWindowViewModel()
{
LoadingPatients();
//instantiƫren DialogService als singleton
dialogService = new DialogService();
}
private void LoadingPatients()
{
//instantiƫren dataservice
PatientDataService patientDS =
new PatientDataService();
Patienten = new ObservableCollection<Patient>(patientDS.GetPatienten());
}
}
Note that I didn't include all of the code so my datacontext is set with a ViewModelLocator which you cannot see here.
Is there any way to save the image as a resource or do I have to convert all the images in the /bin/debug/assets/images folder to a resource at startup? If so how do I do that?
Apologies for my English, I'm not a native speaker
Thanks for those who had the courage to read all the way to this line and thanks for those who can and will help me!
You can load the Image as ImageSource from your file and bind it to an Image in your view.
public class MyViewModel
{
public void LoadImage()
{
ImageSource = new BitmapImage(new Uri("assets/images/yourImage.jpg", UriKind.Relative));
}
public ImageSource ImageSource { get; set; }
}
In the view:
<Image Source="{Binding Path=ImageSource}"></Image>
As answer to the comment, this works also inside a listbox.
The View:
<ListBox ItemsSource="{Binding Path=MyImages}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Source="{Binding Path=ImageSource}"/>
<TextBlock Text="{Binding Path=Name}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
The ViewModel:
public class MainWindowViewModel
{
public void LoadImages()
{
var d = new DirectoryInfo("assets/images");
var images = d.GetFiles();
MyImages = images.Select(x => new MyImageModel(x.Name, new BitmapImage(new Uri(x.FullName))));
}
public IEnumerable<MyImageModel> MyImages { get; set; }
}
The MyImageModel
public class MyImageModel
{
public MyImageModel(string name, ImageSource imageSource)
{
Name = name;
ImageSource = imageSource;
}
public string Name { get; set; }
public ImageSource ImageSource { get; set; }
}

Unable to retrieve image through WCF service in windows phone 8

I followed this guide.
Im able to retrieve all the things in ListBox through WCF EXCEPT image. Can somebody help me?
This is my class
public Tips()
{
//
// TODO: Add constructor logic here
//
}
public int TipsId { get; set; }
public string TipsTitle { get; set; }
public string TipsDescription { get; set; }
public string TipsImage { get; set; }
public string TipsCategory { get; set; }
public string ImageBind { get; set; }
Service.cs
hairtips = new Tips();
hairtips.TipsId = myReader.GetInt32(0);
hairtips.TipsTitle = myReader.GetString(1);
hairtips.TipsDescription = myReader.GetString(2);
hairtips.TipsImage = myReader.GetString(3);
hairtips.TipsCategory = myReader.GetString(4);
tips.Add(hairtips);
After webservice. My .xaml
<ListBox Height="650" HorizontalAlignment="Left" Margin="11,17,0,0" Name="listBox1" VerticalAlignment="Top" Width="434" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock Name="LblTitle" HorizontalAlignment="Left" Margin="0,0,0,0" TextWrapping="Wrap" Text="{Binding TipsTitle}" VerticalAlignment="Top"/>
<TextBlock Name="LblDesc" HorizontalAlignment="Left" Margin="0,0,0,0" TextWrapping="Wrap" Text="{Binding TipsDescription}" VerticalAlignment="Top" Width="400"/>
<Image x:Name="ImageHair" HorizontalAlignment="Stretch" Height="100" Margin="0,0,0,0" VerticalAlignment="Top" Width="100" Source="{Binding TipsImage}" Stretch="Fill"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
My .cs. I have error under imagebind part.
public HairTips()
{
InitializeComponent();
string Category = "Hair";
TipsServiceClient svc = new TipsServiceClient();
svc.getHairTipsCompleted += new EventHandler<getHairTipsCompletedEventArgs>(svc_getHairTipsCompleted);
svc.getHairTipsAsync(Category);
}
void svc_getHairTipsCompleted(object sender, getHairTipsCompletedEventArgs e)
{
List<Tips> listOfTips = new List<Tips>();
foreach (var c in e.Result)
{
Tips tips = new Tips();
tips.TipsTitle = c.TipsTitle;
tips.TipsDescription = c.TipsDescription;
tips.TipsImage = c.TipsImage;
tips.ImageBind = new BitmapImage(new Uri(tips.TipsImage, UriKind.Absolute));
listOfTips.Add(tips);
}
listBox1.ItemsSource = listOfTips;
}
Please help me if you know how to do it. thank you very much
Try using Windows.UI.Xaml.Media.Imaging.BitmapImage than using Windows.Media.Imaging.BitmapImage.
And change your type of ImageBind from String to BitmapImage.
public BitmapImage ImageBind { get; set; }
Reference: Cannot implicitly convert type 'string' to 'Windows.UI.Xaml.Media.Imaging.BitmapImage

how to retrieve multiple images from web service in windows phone 7Thi

I am building an application in windows phone 7 where i need to retrieve multiple images from the web service in a single image view and the images should changes when the user swipes it. I tried it in the following way:
My xaml:
<Image Source="{Binding ImageBind }" HorizontalAlignment="Stretch"
VerticalAlignment="Stretch" Margin="79,61,72,503" Height="187" />
This is my image view where i want to display the images.
The cs code:
public class Rest
{
public string restaurant_image { get; set; }
public BitmapImage ImageBind { get; set; }
}
public const string RestXml = "Rest.xml";
public Restaura()
{
InitializeComponent();
LoadData();
}
private void LoadData()
{
bool isSuccess;
//try to load data from iso store
var doc = ReadXml(out isSuccess);
if (isSuccess) PopulateList(doc);
//if failed (data doesn't exists in iso store), download data from web service
else
{
RahmService.RahmSoapClient client = new RahmService.RahmSoapClient();
client.getRestaurantLocationAllCompleted += new EventHandler<RahmService.getRestaurantLocationAllCompletedEventArgs>(client_getRestaurantLocationAllCompleted);
client.getRestaurantLocationAllAsync();
}
}
void client_getRestaurantLocationAllCompleted(object sender, RahmService.getRestaurantLocationAllCompletedEventArgs e)
{
var doc = XDocument.Parse(e.Result);
PopulateList(doc);
WriteXml(doc);
}
Here i am not getting any result. Please help me with code
Your xaml should be this.
<ListBox Name="ListBoxProduct" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<Image Source="{Binding ImageBind }" HorizontalAlignment="Stretch"
VerticalAlignment="Stretch" Height="187" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
In code behind
private void PopulateList(XDocument doc)
{
List<Rest> restList = new List<Rest>();
foreach (var location in doc.Descendants("UserDetails"))
{
Rest data = new Rest();
data.restaurant_image = location.Element("restaurant_image").Value;
data.ImageBind = new BitmapImage(new Uri(#" http://........"
+ data.restaurant_image, UriKind.Absolute));
restList.Add(data);
}
ListBoxProduct.ItemsSource= restList;
}
Try this.

how to display an image from web service

I am building my first app in windows phone 7. I need to show data from web service along with an image. I am able to show the data but not able to show the image.
My xaml code is:
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ListBox Name="listBox1">
<ListBox.ItemTemplate>
<DataTemplate>
<Button>
<Button.Content>
<ScrollViewer HorizontalScrollBarVisibility="Auto" Height="80" Width="400">
<!--<ScrollViewer Height="80">-->
<StackPanel Orientation="Horizontal" Margin="0,0,0,0">
<StackPanel Orientation="Vertical" Height="80">
<TextBlock Text="{Binding Path=News_Title}" TextWrapping="Wrap" ></TextBlock>
<TextBlock Text="{Binding Path=News_Description}" TextWrapping="Wrap"></TextBlock>
<TextBlock Text="{Binding Path=Date_Start}" TextWrapping="Wrap"></TextBlock>
<Image Source="{Binding Path=Image_Path}" />
</StackPanel>
</StackPanel>
</ScrollViewer>
</Button.Content>
</Button>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
The .cs code is:
public class Newss
{
public string News_Title { get; set; }
public string News_Description { get; set; }
public string Date_Start { get; set; }
}
public News()
{
InitializeComponent();
KejriwalService.aapSoapClient client = new KejriwalService.aapSoapClient();
client.getarvindNewsCompleted += new EventHandler<KejriwalService.getarvindNewsCompletedEventArgs>(client_getarvindNewsCompleted);
client.getarvindNewsAsync();
}
void client_getarvindNewsCompleted(object sender, KejriwalService.getarvindNewsCompletedEventArgs e)
{
string result = e.Result.ToString();
List<Newss> listData = new List<Newss>();
XDocument doc = XDocument.Parse(result);
foreach (var location in doc.Descendants("UserDetails"))
{
Newss data = new Newss();
data.News_Title = location.Element("News_Title").Value;
data.Date_Start = location.Element("Date_Start").Value;
listData.Add(data);
}
listBox1.ItemsSource = listData;
}
}
Xml String:
<NewDataSet>
<UserDetails>
<id>11</id>
<News_Title>Disciplinary Action against Vinod Binny</News_Title>
<News_Description>The Aam Aadmi Party formed a disciplinary committee, on 19-Jan-2013, headed by Pankaj Gupta to look into the matter of Vinod Kumar Binny. The other members of the committee included Ashish Talwar, Illyas Azmi, Yogendra Yadav and Gopal Rai.
This disciplinary committee has decided to expel Vinod Kumar Binny and terminate his primary membership from the party, for publicly making false statements against the party and its leadership, thereby bringing disrepute to the party. A letter to the same end has been issued to Vinod Kumar Binny.</News_Description>
<Date_Start>2014-01-29</Date_Start>
<image_path>news.png</image_path>
Can anyone help me in displaying the images for each field.
The image path is an http url
http://political-leader.vzons.com/ArvindKejriwal/images/uploaded/news.png
If i guess right your Image_Path is a http url . so you need to BitmapImage to bind as a ImageSource. may this will help you.
public class Newss
{
public string News_Title { get; set; }
public string News_Description { get; set; }
public string Date_Start { get; set; }
**//Edits**
public string image_path {get;set}
public BitmapImage ImageBind{get;set;}
}
foreach (var location in doc.Descendants("UserDetails"))
{
Newss data = new Newss();
data.News_Title = location.Element("News_Title").Value;
data.Date_Start = location.Element("Date_Start").Value;
**//Edits**
data.image_path = location.Element("Image_Path").Value;
data.ImageBind = new BitmapImage(new Uri( #"http://political-leader.vzons.com/ArvindKejriwal/images/uploaded/"+data.image_path, UriKind.Absolute)
listData.Add(data);
}
**Your xaml changes**
<Image Source="{Binding ImageBind }" />

Loading Images into ListBox

I want to display images into a ListBox in WPF. What i want to achieve is following
Read from a device for images and get information like name etc. (DONE)
create items in listbox and display default thumb (some default pic) in place of actual thumb as thumb will be read later for the image. (DONE)
Now get their thumbnails and store them in a folder (DONE). Being done by a task.
NOW show the actual thumb of the image. ( NOT DONE).
STEP 4 is where i am stuck. Basically what i want to do is similar to windows which will first display images/videos icon then fill their thumbs.
Please help. I am new to WPF and hence facing problems.
<ListBox ItemsSource="{Binding Items}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Margin="5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50"/>
<ColumnDefinition Width="10"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Image Source="{Binding Image}"/>
<Grid Grid.Column="2">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock Text="{Binding Name}"/>
<TextBlock Grid.Row="1" Text="{Binding Desc}"/>
<TextBlock Grid.Row="2" Text="{Binding Notes}"/>
</Grid>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
public partial class ImageListBox : INotifyPropertyChanged
{
private ObservableCollection<Item> _items;
public ObservableCollection<Item> Items
{
get { return _items; }
set { _items = value; OnPropertyChanged("Items"); }
}
public ImageListBox()
{
DataContext = this;
Items = new ObservableCollection<Item>(new List<Item>
{
new Item { Image = "Images/_(1).png" , Desc = "Desc1",Name = "Name1",Notes = "Notes1"},
new Item { Image = "Images/_(2).png" , Desc = "Desc2",Name = "Name2",Notes = "Notes2"},
new Item { Image = "Images/_(3).png" , Desc = "Desc3",Name = "Name3",Notes = "Notes3"},
new Item { Image = "Images/_(4).png" , Desc = "Desc4",Name = "Name4",Notes = "Notes4"},
new Item { Image = "Images/_(5).png" , Desc = "Desc5",Name = "Name5",Notes = "Notes5"},
});
InitializeComponent();
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(String propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this,new PropertyChangedEventArgs(propertyName));
}
}
public class Item
{
public String Image { get; set; }
public String Name { get; set; }
public String Desc { get; set; }
public String Notes { get; set; }
}
I might not properly understand your question but if i got it right: you want to display an image in some WPF control.
1) Bind path to your image to the control (I used DataGrid):
<DataGrid ItemsSource="{Binding Path=ImageCollection}"
<DataGrid.Columns>
<DataGridTemplateColumn Header="Image">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Image Width="40" Height="20" Source="{Binding FilePath, Converter={StaticResource ResourceKey=ImageConverter}}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid>
2) Create converter that converts FilePath to ImageSource (I found it somewhere in the Internet):
public class ImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var path = value as string;
if (path == null)
{
return DependencyProperty.UnsetValue;
}
//create new stream and create bitmap frame
var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
try
{
bitmapImage.StreamSource = new FileStream(path, FileMode.Open, FileAccess.Read);
//load the image now so we can immediately dispose of the stream
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
//clean up the stream to avoid file access exceptions when attempting to delete images
bitmapImage.StreamSource.Dispose();
return bitmapImage;
}
catch (Exception)
{
//do smth
}
}
}
Hope, this helps.
There are various approachs to this, one would be using a PriorityBinding which first displays the placeholder icon, then the thumb. (You probably need to assign the property which holds the image only after it is fully loaded.)

Categories

Resources