updating an image in an image control - c#

im trying to update an image in an image control that is bound to a class which implements INotifyPropertyChanged. i've tried most of the methods which relate to refreshing bitmap cache so that the image can refresh but none seems to work for my case. the image contorl is defined in the xaml file as: <Image Source="{Binding Chart}" Margin="0 0 0 0"/>
and in the code behind the class is:
private ImageSource imagechart = null;
public ImageSource Chart
{
get
{
return imagechart;
}
set
{
if (value != imagechart)
{
imagechart = value;
NotifyPropertyChanged("Chart");
}
}
}
after an event i now set the image using the following code:
c.Chart = image;
when i now run my application this will display the image but during the running of the application i update the image but calling this c.Chart = image; displays the initial image. i came to understand that WPF caches the image but all methods claiming to solve this dint work for me. one of the solutions that did not work for me is Problems overwriting (re-saving) image when it was set as image source

Try to change the return Type of your Image property to Uri. The TypeConverter on the Source Property should do the rest. If this doesnt work, verify that the resource has actually changed.
You can read the resource from your assembly using Assembly.GetManifestResourceStreams and resolve the bytes. Than manually save them with File.WriteAllBytes to your output directory an see if it has the expected image.
As far as i know Application Ressources (which are embedded into the assembly) can not be changed during runtime (?). You are referencing the assembly ressource and not an output ressource with your pack uri.

thank you all for your input coz through them i finally figure a way around this. so my xaml still remains bound as <Image Source="{Binding Chart}" Margin="0 0 0 0"/> but in the code behind i changed the class property chart to return a bitmap as shown below:
private BitmapImage image = null;
public BitmapImage Chart
{
get
{
return image;
}
set
{
if (value != image)
{
image = value;
NotifyPropertyChanged("Chart");
}
}
}
this class mind you implements INotifyPropertyChanged . at the point where i set the image i am now using this code:
BitmapImage img = new BitmapImage();
img.BeginInit();
img.CacheOption = BitmapCacheOption.OnLoad;
img.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
//in the following code path is a string where i have defined the path to file
img.UriSource = new Uri(string.Format("file://{0}",path));
img.EndInit();
c.Chart = img;
this works well for me and refreshes the image upon update.

Related

Bringing large image into view at runtime

Here is the problem.
I have a view, that should display an image and some controls.
User add new images, changes some options and click "finish".
Images are large and very large (400-1500 MB Tiff)
User should see the preview of image, but it is ok if it loading for 10-15 sec or even more, he have a job for this time.
Image is binding through MVVM pattern like simple string (file will be always in local folder)
<Image Name="ImagePreview" Source="{Binding SFilePathForPreview,
FallbackValue={StaticResource DefaultImage},
TargetNullValue={StaticResource DefaultImage}}"
HorizontalAlignment="Center" Width="200" Height="200"
VerticalAlignment="Center" />
Problem is that all is hangs when user try to add a file for loading time.
I understand that this case should be solved through multithreading - but have no idea how to implement this.
I tryed to update image from view in different thread like this:
Thread newThread = new Thread(LazyLoad);
newThread.Name = "LazyLoad";
newThread.Start(SFilePathForPreview);
public void LazyLoad(object SFilePath)
{
try
{
string path = (string)SFilePath;
BitmapImage t_source = new BitmapImage();
t_source.BeginInit();
t_source.UriSource = new Uri(path);
t_source.DecodePixelWidth = 200;
t_source.EndInit();
t_source.Freeze();
this.Dispatcher.Invoke(new Action(delegate
{
ImagePreview.Source = t_source;
}));
}
catch
{
//...
}
}
But anyway at point
ImagePreview.Source = t_source;
everything hangs up until image fully loaded.
Is there a way to load a preview in the background and show it without those terrible hangs?
The probably most simple way of asynchronously loading an image is via an asynchronous Binding. You would not have to deal with Threads or Tasks at all.
<Image Source="{Binding Image, IsAsync=True}"/>
A possible view model could look like shown below, where you must make sure that the Image property getter can be called from a background thread.
public class ViewModel : ViewModelBase
{
private string imagePath;
private BitmapImage image;
public string ImagePath
{
get { return imagePath; }
set
{
imagePath = value;
image = null;
OnPropertyChanged(nameof(ImagePath));
OnPropertyChanged(nameof(Image));
}
}
public BitmapImage Image
{
get
{
lock (this)
{
if (image == null &&
!string.IsNullOrEmpty(imagePath) &&
File.Exists(imagePath))
{
using (var stream = File.OpenRead(imagePath))
{
image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.DecodePixelWidth = 200;
image.StreamSource = stream;
image.EndInit();
image.Freeze();
}
}
}
return image;
}
}
}
As you already mentioned, you are blocking the UI thread with the image load. You can use a WriteableBitmap class instance as the source for your Image. This will let you load the image on a background thread or async task. Here is a quick guide (not mine) on the issue.
https://www.i-programmer.info/programming/wpf-workings/527-writeablebitmap.html
Another option would be using priortybinding with the highest priorty to the full image and a lower priority to the faster-loading preview image. MS has documented priority binding here:
https://learn.microsoft.com/en-us/dotnet/framework/wpf/data/how-to-implement-prioritybinding

Image Control in Wpf showing previous image which was deleted

I have an image control which is showing the preview image. If the user delete the image (which resides in folder) it should show the newly taken image.
but the image control shows the deleted image instead of showing new image.
// clear the image source before deleting the image.
// save image in the directory
public string globalFilePath;
int imageCount = Directory.GetFiles(imgDir, "*", SearchOption.TopDirectoryOnly).Length;
string filePath = Path.Combine(imgDir, "IMAGE_" + ++imageCount + ".jpeg");
globalFilePath = filePath;
// setting image control source
var strUri = new Uri(WebCamControl.globalFilePath, UriKind.Relative);
previewImage.Source = BitmapFromUri(strUri);
//Method
public static ImageSource BitmapFromUri(Uri source)
{
var bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.UriSource = source;
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.EndInit();
return bitmap;
}
// delete image
previewImage.Source = null;
if (System.IO.File.Exists(WebCamControl.globalFilePath))
{
System.IO.File.Delete(WebCamControl.globalFilePath);
}
else
{
MessageBox.Show("File Not Exists");
}
After deleting the image in the directory file the image image control should show the new image, but my Image control shows the deleted image. please give me the solution.
In WPF, we generally don't need to use actual BitMapImage objects to display an Image. It's far easier to let the .NET Framework convert our string file paths to the images to the actual Image elements.
Also, it is far better to data bind the Image.Source to a property that implements the INotifyPropertyChanged interface (or a DepenedencyProperty):
<Image Source="{Binding YourImageFilePath}" ... />
Then, whenever a file path of a new image is set to the YourImageFilePath property, your displayed image will update immediately.
YourImageFilePath = filePath;
Try This one:
string path = ((BitmapImage)img.Source).UriSource.LocalPath;
img.SetValue(System.Windows.Controls.Image.SourceProperty, null);
File.Delete(path);
OR
string path = ((BitmapImage)img.Source).UriSource.LocalPath;
img.Source = null;
File.Delete(path)

Control background bound to image not updating

Note: This is for a Windows RT App (Windows Store app).
I am having a strange issue when I am trying to bind the background of a button to an image that is stored on the device.
Basically my set up is as follows:
I have a button that, when pressed, presents a flyout that has a canvas in which the user can draw something using an InkManager. Once the flyout closes, it saves that ink data to a .png file.
The button itself has its Background bound to the path of the .png file which does implement INotifyPropertyChanged:
XAML:
<Button.Background>
<Binding Converter="{StaticResource FileNameToImage}" Path="PicFilePath"/>
</Button.Background>
Code behind:
public string PicFilePath
{
get { return picFilePath; }
set
{
//This is commented out because I want to reuse the same file name, which would cause this to not notify that the property was changed.
//if (value == picFilePath) return;
picFilePath = value;
OnPropertyChanged();
}
}
It then uses a converter to convert that path to an ImageBrush that has that image as its background:
public object Convert(object value, Type targetType, object parameter, string language)
{
try
{
string fileName = value.ToString();
var brush = new ImageBrush();
Uri sigUri = new Uri(fileName);
brush.ImageSource = new BitmapImage(sigUri);
return brush;
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
var brush = new SolidColorBrush(Colors.White);
return brush;
}
}
My issue is stemming from the fact that I am attempting to reuse the same file name when I create the file after the user finishes drawing:
StorageFile myMerge = await currSessionFolder.CreateFileAsync(PicFileName, CreationCollisionOption.ReplaceExisting);
oStream = await myMerge.OpenAsync(FileAccessMode.ReadWrite);
if (oStream != null)
{
await mainInkManager.SaveAsync(oStream);
}
//Here is where I reset the data context's PicFilePath
globalContext.PicFilePath = myMerge.Path;
This works the first time through but if I go back and add more strokes to the canvas and close it, the button retains the same background that it had before, even though I can step through the code and verify that it is going through the OnPropertyChanged and convert process which should give it a new ImageBrush for the background. I can even browse the file system to the actual png file and see that it is updated with the new strokes before the button is supposed to update.
On top of that this works 100% as I intend it to if I use a unique file name for each modification of the canvas. So if I draw a smiley face and save it as smiley.png, when I close the flyout the button will update with that image. If I open it back up and save it as smiley2.png and close it, it updates the button just fine. My issue is that I don't want to have to resave the image with a new name every time and I can't see why this isn't working when I reuse the same file name.
Any ideas?

Displaying animated GIF files from embedded resources

I'm trying to display an animated GIF on a form from an embedded resource, yet nothing is displayed, which makes me think loading from a stream doesn't work this way.
If I ditch this idea and load from file, the GIF is displayed correctly.
Is this something that just won't work, or have I made a mistake along the way? Also, this is being done from within a DLL.
My Code:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
// Set the image
this.pictureBox.Image = GetImageFromManifest("TempNamespace.Wait.gif");
// Remove the close button
var hwnd = new WindowInteropHelper(this).Handle;
SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) & ~WS_SYSMENU);
}
public System.Drawing.Image GetImageFromManifest(string sPath)
{
// Ready the return
System.Drawing.Image oImage = null;
try
{
// Get the assembly
Assembly oAssembly = Assembly.GetAssembly(this.GetType());
string[] names = oAssembly.GetManifestResourceNames();
// Get the stream
Stream oStream = oAssembly.GetManifestResourceStream(sPath);
// Read from the stream
oImage = System.Drawing.Image.FromStream(oStream);
}
catch (Exception ex)
{
// Missing image?
}
//Return the image
return oImage;
}
My XAML:
<wfi:WindowsFormsHost HorizontalAlignment="Center" VerticalAlignment="Center" Height="50" Width="50">
<winForms:PictureBox x:Name="pictureBox" Height="50" Width="50" SizeMode="StretchImage" BackgroundImageLayout="None"/>
</wfi:WindowsFormsHost>
In summary, the problem was caused by setting the form's 'SizeToContent' value in either the XAML or the constructor (in my case, it was set to 'SizeToContent.WidthAndHeight').
Removing this property, and setting it in the 'Loaded' event rectified the issue. I assume that the Windows Form Host doesn't render correctly with animated GIF files when the form itself is not painted.

Why do I get an OutOfMemoryException when I have images in my ListBox?

I want to display all images stored in the Windows Phone 8 photo folder in my custom gallery which uses a ListBox for displaying the images.
The ListBox code is as follows:
<phone:PhoneApplicationPage.Resources>
<MyApp:PreviewPictureConverter x:Key="PreviewPictureConverter" />
</phone:PhoneApplicationPage.Resources>
<ListBox Name="previewImageListbox" VirtualizingStackPanel.VirtualizationMode="Recycling">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel CleanUpVirtualizedItemEvent="VirtualizingStackPanel_CleanUpVirtualizedItemEvent_1">
</VirtualizingStackPanel>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Image Source="{Binding Converter={StaticResource PreviewPictureConverter}}" HorizontalAlignment="Center" VerticalAlignment="Center" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
With the following converter:
public class PreviewPictureConverter : System.Windows.Data.IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
PreviewImageItem c = value as PreviewImageItem;
if (c == null)
return null;
return c.ImageData;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
Images are stored in a custom class:
class PreviewImageItem
{
public Picture _picture = null;
public BitmapImage _bitmap = null;
public PreviewImageItem(Picture pic)
{
_picture = pic;
}
public BitmapImage ImageData
{
get
{
System.Diagnostics.Debug.WriteLine("Get picture " + _picture.ToString());
_bitmap = new BitmapImage();
Stream data = _picture.GetImage();
try
{
_bitmap.SetSource(data); // Out-of memory exception (see text)
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Exception : " + ex.ToString());
}
finally
{
data.Close();
data.Dispose();
data = null;
}
return _bitmap;
}
}
}
The following code is used to set the ListBox data source:
private List<PreviewImageItem> _galleryImages = new List<PreviewImageItem>();
using (MediaLibrary library = new MediaLibrary())
{
PictureCollection galleryPics = library.Pictures;
foreach (Picture pic in galleryPics)
{
_galleryImages.Add(new PreviewImageItem(pic));
}
previewImageListbox.ItemsSource = _galleryImages;
};
Finally here is the "cleanup" code:
private void VirtualizingStackPanel_CleanUpVirtualizedItemEvent_1(object sender, CleanUpVirtualizedItemEventArgs e)
{
PreviewImageItem item = e.Value as PreviewImageItem;
if (item != null)
{
System.Diagnostics.Debug.WriteLine("Cleanup");
item._bitmap = null;
}
}
All this works fine but the code crashes with an OutOfMemoryException after a few images (especially when scrolling fast). The method VirtualizingStackPanel_CleanUpVirtualizedItemEvent_1 is called regulary (e.g. every 2 or 3 listbox entries) when the ListBox is scrolled.
What's wrong with this sample code?
Why is memory not freed (fast enough)?
Oh, I recently killed whole day to make this working!
So the solution is:
Make your Image control free resources. So set the
BitmapImage bitmapImage = image.Source as BitmapImage;
bitmapImage.UriSource = null;
image.Source = null;
as it was mentioned before.
Make sure you virtualize _bitmap on every item of the list. You should load it on demand (LongListSelector.Realized method) and you have to destroy it! It won't going to collect automatically and GC.Collect doesn't work either.
Null reference is not working too :(
But here is the method:
Make 1x1 pixel file. Copy it into assembly and make resource stream from it to dispose your images with 1x1 pixel blank. Bind custom dispose method to LongListSelector.UnRealized event (e.Container handles your list item).
public static void DisposeImage(BitmapImage image)
{
Uri uri= new Uri("oneXone.png", UriKind.Relative);
StreamResourceInfo sr=Application.GetResourceStream(uri);
try
{
using (Stream stream=sr.Stream)
{
image.DecodePixelWidth=1; //This is essential!
image.SetSource(stream);
}
}
catch { }
}
Working for me in LongListSelector with 1000 images 400 width each.
If you miss the 2 step with the data collection you can see the the good results but the memory overflows after 100-200 items scrolled.
You just had Windows Phone with show all the picture's in a user's media library "pictures" folder on screen. That's unbelievably memory intensive and considering the 150MB limit on WP8 apps it's no wonder you're getting OOM exceptions.
A few things you should consider adding:
1) Set Source and SourceUri properties to null when scrolling the listboxitem out of view. See "Caching Images" in Stefan's article here # http://blogs.msdn.com/b/swick/archive/2011/04/07/image-tips-for-windows-phone-7.aspx
BitmapImage bitmapImage = image.Source as BitmapImage;
bitmapImage.UriSource = null;
image.Source = null;
2) If you're on WP8 make sure to set DecodePixelWidth and/or DecodePixelHeight. That way an image will be loaded into memory, resized permanently and only the resized copy is stored in memory. The images loaded into memory can be much bigger then the screen size of the phone itself. So cropping those down to the right size and only storing the resized images is vital. Set BitmapImage.DecodePixelWidth=480 (at maximum) to help with that.
var bmp = new BitmapImage();
// no matter the actual size,
// this bitmap is decoded to 480 pixels width (aspect ratio preserved)
// and only takes up the memory needed for this size
bmp.DecodePixelWidth = 480;
bmp.UriSource = new Uri(#"Assets\Demo.png", UriKind.Relative);
ImageControl.Source = bmp;
(code sample from here)
3) Why are you using Picture.GetImage() instead of Picture.GetThumbnail()? Do you really need the image to take up the whole screen?
4) Consider moving from ListBox to LongListSelector if this is a WP8 exclusive app. LLS has much, much better virtualization then ListBox. Looking at your code sample it might be enough for you to just change your XAML ListBox element to LongListSelector element.
Try this approach: Image downloader with auto memory cleaning. Sample project here: https://simca.codeplex.com/

Categories

Resources