Delete image file used by XAML - wpf

I'm trying to delete a Image file in WPF, but WPF locks the file.
<Image Source="C:\person.gif" x:Name="PersonImage">
<Image.ContextMenu>
<ContextMenu>
<MenuItem Header="Delete..." x:Name="DeletePersonImageMenuItem" Click="DeletePersonImageMenuItem_Click"/>
</ContextMenu>
</Image.ContextMenu>
</Image>
And the Click handler just looks like this:
private void DeletePersonImageMenuItem_Click(object sender, RoutedEventArgs e)
{
System.IO.File.Delete(#"C:\person.gif");
}
But, when I try to delete the file it is locked and cannot be removed.
Any tips on how to delete the file?

My application Intuipic deals with this by using a custom converter that frees the image resource. See the code here.

Using code behind, you can use the cache option BitmapCacheOption.OnLoad:
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.CacheOption = BitmapCacheOption.OnLoad;
bi.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
bi.UriSource = new Uri(PathToImage);
bi.EndInit();
PersonImage.Source = bi;
Because I struggled to find it, I will add that if you want to replace the deleted image dynamically, you need to add the argument BitmapCreateOptions.IgnoreImageCache.

First Remove it from the PersonImage control then delete the image. Hope that will help.
As you have assigned to the control in source, and remove it without unassigning the control source.
PersonImage.Source = null;
System.IO.File.Delete(#"C:\person.gif");
hope that will help.

The most easiest way to do this will be, creating a temporary copy of your image file and using it as a source.. and then at end of your app, deleting all temp files..
static List<string> tmpFiles = new List<string>();
static string GetTempCopy(string src)
{
string copy = Path.GetTempFileName();
File.Copy(src, copy);
tmpFiles.Add(copy);
return copy;
}
static void DeleteAllTempFiles()
{
foreach(string file in tmpFiles)
{
File.Delete(file);
}
}
Image caching in WPF also can be configured to do this, but for some reason my various attempts failed and we get unexpected behaviour like not being able to delete or refresh the image etc, so we did this way.

Do not attach the physical file to the object.
BitmapImage bmp;
static int filename = 0;
static string imgpath = "";
private void saveButton_Click(object sender, RoutedEventArgs e)
{
try
{
filename = filename + 1;
string locimagestored = Directory.GetParent(Assembly.GetExecutingAssembly().Location).ToString();
locimagestored = locimagestored + "\\StoredImage\\";
imgpath = locimagestored + filename + ".png";
webCameraControl.GetCurrentImage().Save(imgpath);
Bitmap bitmap = new Bitmap(#imgpath);
IntPtr hBitmap = bitmap.GetHbitmap();
ImageSource wpfBitmap = Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); ;
if (filename == 1)
{
imgSavedOnline0.Source = wpfBitmap;
bitmap.Dispose();
}
else if (filename == 2)
{
imgSavedOnline1.Source = wpfBitmap;
bitmap.Dispose();
}
else if (filename == 3)
{
imgSavedOnline2.Source = wpfBitmap;
bitmap.Dispose();
}
else if (filename == 4)
{
imgSavedOnline3.Source = wpfBitmap;
bitmap.Dispose();
}
System.IO.DirectoryInfo di2 = new DirectoryInfo(locimagestored);
foreach (FileInfo file in di2.GetFiles())
{
file.Delete();
}
}
catch (Exception ex)
{
textBox1.Text = ex.Message;
}
}

Related

Update WPF UI from Different Thread VB.net [duplicate]

Here's my problem.
I'm loading a few BitmapImages in a BlockingCollection
public void blockingProducer(BitmapImage imgBSource)
{
if (!collection.IsAddingCompleted)
collection.Add(imgBSource);
}
the loading happens in a backgroungwork thread.
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
String filepath; int imgCount = 0;
for (int i = 1; i < 10; i++)
{
imgCount++;
filepath = "Snap";
filepath += imgCount;
filepath += ".bmp";
this.Dispatcher.BeginInvoke(new Action(() =>
{
label1.Content = "Snap" + imgCount + " loaded.";
}), DispatcherPriority.Normal);
BitmapImage imgSource = new BitmapImage();
imgSource.BeginInit();
imgSource.UriSource = new Uri(filepath, UriKind.Relative);
imgSource.CacheOption = BitmapCacheOption.OnLoad;
imgSource.EndInit();
blockingProducer(imgSource);
}
}
debugging this part of the code everything looks okay, the problem comes now ...
after finishing loading the images I want to show them in UI one by one. I'm using a dispatcher to do so but I always get the message telling me that the called Thread can not access the object because it belongs to a different Thread.
public void display(BlockingCollection<BitmapImage> results)
{
foreach (BitmapImage item in collection.GetConsumingEnumerable())
{
this.Dispatcher.BeginInvoke(new Action(() =>
{
this.dstSource.Source = item;
Thread.Sleep(250);
}), DispatcherPriority.Background);
}
}
debug accuses that the error is here
this.dstSource.Source = item;
I'm trying everything but cant find out what’s wrong. Anyone has any idea?
You have to call Freeze after loading the images in order to make them accessible to other threads:
BitmapImage imgSource = new BitmapImage();
imgSource.BeginInit();
imgSource.UriSource = new Uri(filepath, UriKind.Relative);
imgSource.CacheOption = BitmapCacheOption.OnLoad;
imgSource.EndInit();
imgSource.Freeze(); // here
As far as I have understood the BitmapCacheOption.OnLoad flag, it is only effective when a BitmapImage is loaded from a stream. The Remarks section in BitmapCacheOption says:
Set the CacheOption to BitmapCacheOption.OnLoad if you wish to close a
stream used to create the BitmapImage. The default OnDemand cache
option retains access to the stream until the image is needed, and
cleanup is handled by the garbage collector.
A BitmapImage created from a Uri may be loaded asynchronously (see the IsDownloading property). Consequently, Freeze may not be callable on such a BitmapImage, as downloading may still be in progress after EndInit. I guess it nevertheless works in your case because you are loading BitmapImages from file Uris, which seems to be done immediately.
To avoid this potential problem you may just create the BitmapImage from a FileStream:
var imgSource = new BitmapImage();
using (var stream = new FileStream(filepath, FileMode.Open))
{
imgSource.BeginInit();
imgSource.StreamSource = stream;
imgSource.CacheOption = BitmapCacheOption.OnLoad;
imgSource.EndInit();
imgSource.Freeze();
}
For the further future readers, here is the code I used to fix my problem.
public void display(BlockingCollection<BitmapImage> collection)
{
if (collection.IsCompleted || collection.Count != 0)
{
BitmapImage item = collection.Take();
this.Dispatcher.BeginInvoke(new Action(() =>
{
this.dstSource.Source = item;
}), DispatcherPriority.Normal);
}
else
{
dispatcherTimer.Stop();
}
}
public void dispatcherTimer_Tick(object sender, EventArgs e)
{
display(collection);
}
public void configureDispatcherTimer()
{
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
TimeSpan interval = TimeSpan.FromMilliseconds(150);
dispatcherTimer.Interval = interval;
}

Displaying an Image from a DB in an Image Control

I've saved an image in my DataBase in a parameter type image and I've done this with:
private void btnAceptar_Click(object sender, RoutedEventArgs e)
{
UsuariosBLL bll = new UsuariosBLL();
UsuariosBO user = new UsuariosBO();
PerfilBO perfil = cmbperf.SelectedItem as PerfilBO;
//........
user.Imagen = ConvertImageToByteArray(ruta);
bll.InsertarFilaUsuarios(user);
MessageBox.Show("Se insertó");
//.......
}
where the method ConvertToByteArray convert the image selected in a Byte Array
public byte[] ConvertImageToByteArray(string path)
{
byte[] ImageByte=null;
try
{
FileStream fs = new FileStream(path,FileMode.Open,FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
ImageByte = br.ReadBytes((int)fs.Length);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return ImageByte;
}
and now I just wanna retrieve the image selecting a different user in my combobox.
I've tried like this:
private void cmbUsuarios_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
UsuariosBO user = e.AddedItems[0] as UsuariosBO;
//.....
MemoryStream ms = new MemoryStream(user.Imagen);
System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
imgFoto = img;
usuario = user;
}
But a error born:
Can not implicitly convert type 'System.Drawing.Image' to 'System.Windows.Controls.Image'
I understand what it means but I don't know how to fix it...
thanks !!
Instead of creating a System.Drawing.Image from the byte stream, you should create a WPF ImageSource and assign that to the Source property of your ImageControl.
One way to do this is by creating a BitmapImage:
using (var ms = new MemoryStream(user.Imagen))
{
var img = new BitmapImage();
img.BeginInit();
img.CacheOption = BitmapCacheOption.OnLoad;
img.StreamSource = ms;
img.EndInit();
imgFoto.Source = img;
}
Or alternatively a BitmapFrame:
using (var ms = new MemoryStream(user.Imagen))
{
imgFoto.Source = BitmapFrame.Create(ms,
BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
}

Loading Images in background while not locking the files

My application loads a lot of images in a BackgroundWorker to stay usable. My Image control is bound to a property named "ImageSource". If this is null it's loaded in the background and raised again.
public ImageSource ImageSource
{
get
{
if (imageSource != null)
{
return imageSource;
}
if (!backgroundImageLoadWorker.IsBusy)
{
backgroundImageLoadWorker.DoWork += new DoWorkEventHandler(bw_DoWork);
backgroundImageLoadWorker.RunWorkerCompleted +=
new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
backgroundImageLoadWorker.RunWorkerAsync();
}
return imageSource;
}
}
void bw_DoWork(object sender, DoWorkEventArgs e)
{
bitmap = new BitmapImage();
bitmap.BeginInit();
try
{
bitmap.CreateOptions = BitmapCreateOptions.DelayCreation;
bitmap.DecodePixelWidth = 300;
MemoryStream memoryStream = new MemoryStream();
byte[] fileContent = File.ReadAllBytes(imagePath);
memoryStream.Write(fileContent, 0, fileContent.Length);
memoryStream.Position = 0;
bitmap.StreamSource = memoryStream;
}
finally
{
bitmap.EndInit();
}
bitmap.Freeze();
e.Result = bitmap;
}
void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
BitmapSource bitmap = e.Result as BitmapSource;
if (bitmap != null)
{
Dispatcher.CurrentDispatcher.BeginInvoke(
(ThreadStart)delegate()
{
imageSource = bitmap;
RaisePropertyChanged("ImageSource");
}, DispatcherPriority.Normal);
}
}
This is all well so far but my users can change the images in question. They choose a new image in an OpenDialog, the old image file is overwritten with the new and ImageSource is raised again which loads the new image with the same filename again:
public string ImagePath
{
get { return imagePath; }
set
{
imagePath= value;
imageSource = null;
RaisePropertyChanged("ImageSource");
}
}
On some systems the overwriting of the old file results in an exception:
"a generic error occured in GDI+" and "The process cannot access the file..."
I tried a lot of things like loading with BitmapCreateOptions.IgnoreImageCache and BitmapCacheOption.OnLoad. This raised Exceptions when loading them:
Key cannot be null.
Parameter name: key
If I try this without the BackgroundWorker on the UI thread it works fine. Am I doing something wrong? Isn't it possible to load the images in the background while keeping the files unlocked?
Well, it seems all of the above works. I simplified the example for the question and somehow on the way lost the problem.
The only difference I could see in my code is that the loading of the image itself was delegated to a specific image loader class which somehow created the problem. When I removed this dependency the errors disappeared.

How can I save and open a file in winForms?

I have this application where I use windowsForm and UserControl to draw some diagrams. After I am done I want to save them or I want to open an existing file that I created before and keep working on the diagram. So, I want to use the save and open dialog File to save or open my diagrams.
EDIT:
this is what i have :
//save the object to the file
public bool ObjectToFile(Object model, string FileName)
{
try
{
System.IO.MemoryStream _MemoryStream = new System.IO.MemoryStream();
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter _BinaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
_BinaryFormatter.Serialize(_MemoryStream, model);
byte[] _ByteArray = _MemoryStream.ToArray();
System.IO.FileStream _FileStream = new System.IO.FileStream(FileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
_FileStream.Write(_ByteArray.ToArray(), 0, _ByteArray.Length);
_FileStream.Close();
_MemoryStream.Close();
_MemoryStream.Dispose();
_MemoryStream = null;
_ByteArray = null;
return true;
}
catch (Exception _Exception)
{
Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
}
return false;
}
//load the object from the file
public Object FileToObject(string FileName)
{
try
{
System.IO.FileStream _FileStream = new System.IO.FileStream(FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
System.IO.BinaryReader _BinaryReader = new System.IO.BinaryReader(_FileStream);
long _TotalBytes = new System.IO.FileInfo(FileName).Length;
byte[] _ByteArray = _BinaryReader.ReadBytes((Int32)_TotalBytes);
_FileStream.Close();
_FileStream.Dispose();
_FileStream = null;
_BinaryReader.Close();
System.IO.MemoryStream _MemoryStream = new System.IO.MemoryStream(_ByteArray);
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter _BinaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
_MemoryStream.Position = 0;
return _BinaryFormatter.Deserialize(_MemoryStream);
}
catch (Exception _Exception)
{
Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
}
return null;
}
and now I want to do this but it's not working
public void save()
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt files (*.txt)|*.txt";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if (saveFileDialog1.OpenFile() != null)
{
ObjectToFile(model, saveFileDialog1.FileName);
}
}
}
but if I try without the fileDialog and i just use
ObjectToFile(model, "d:\\objects.txt");
this works. And I want to save it where I want and with my own name.
Check out the SaveFileDialog and OpenFileDialog classes. They are pretty similar, and can be used like this:
using(SaveFileDialog sfd = new SaveFileDialog()) {
sfd.Filter = "Text Files|*.txt|All Files|*.*";
if(sfd.ShowDialog() != DialogResult.OK) {
return;
}
ObjectToFile(sfd.FileName);
}
The mechanics of actually saving your file are, obviously, outside the scope of this answer.
Edit: I've updated my answer to reflect the new information in your post.

WPF loading serialized image

In an app I need to serialize an image through a binarywriter, and to get it in an other app to display it.
Here is a part of my "serialization" code :
FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write);
BinaryWriter bin = new BinaryWriter(fs);
bin.Write((short)this.Animations.Count);
for (int i = 0; i < this.Animations.Count; i++)
{
MemoryStream stream = new MemoryStream();
BitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(Animations[i].Image));
encoder.Save(stream);
stream.Seek(0, SeekOrigin.Begin);
bin.Write((int)stream.GetBuffer().Length);
bin.Write(stream.GetBuffer());
stream.Close();
}
bin.Close();
And here is the part of my deserialization that load the image :
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
BinaryReader bin = new BinaryReader(fs);
int animCount = bin.ReadInt16();
int imageBytesLenght;
byte[] imageBytes;
BitmapSource img;
for (int i = 0; i < animCount; i++)
{
imageBytesLenght = bin.ReadInt32();
imageBytes = bin.ReadBytes(imageBytesLenght);
img = new BitmapImage();
MemoryStream stream = new MemoryStream(imageBytes);
BitmapDecoder dec = new PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
img = dec.Frames[0];
stream.Close();
}
bin.Close();
When I use this method, I load the image (it seems to be stored in the "img" object) but it can't be displayed.
Has somedy an idea?
Thanks
KiTe
UPD :
I already do this : updating my binding, or even trying to affect it directly through the window code behing. None of these approaches work :s
However, when I add this :
private void CreateFile(byte[] bytes)
{
FileStream fs = new FileStream(Environment.CurrentDirectory + "/" + "testeuh.png", FileMode.Create, FileAccess.Write);
fs.Write(bytes, 0, bytes.Length);
fs.Close();
}
at the end of you function, it perfectly create the file, which can be read without any problems ... So I don't know where the problem can be.
UPD 2 :
A weird things happens.
Here is the binding I use :
<Image x:Name="imgSelectedAnim" Width="150" Height="150" Source="{Binding ElementName=lstAnims, Path=SelectedItem.Image}" Stretch="Uniform" />
(the list is itself binded on an observableCollection).
When I create manually the animation through the app, it works (the image is displayed).
But when I load it, it is not displayed (I look at my code, there are not any "new" which could break up my binding, since there are others properties binded the same way and they does not fail).
Moreover, I've put a breakpoint on the getter/setter of the properties Image of my animation.
When it is created, no problems, it has the good informations.
But when it is retreived through the getter, it return a good image the first time, and then and image with pixelWidth, pixelHeight, width, height of only 1 but without going through the setter anymore !
Any idea?
UPD3
tried what you said like this :
Added a property TEST in my viewModel :
private BitmapSource test;
public BitmapSource TEST { get { return test; } set { test = value; RaisePropertyChanged("TEST"); } }
then did it :
img = getBmpSrcFromBytes(bin.ReadBytes(imageBytesLenght));
TEST = img;
(in the code showed and modified before)
and my binding :
<Image x:Name="imgSelectedAnim" Width="150" Height="150" Source="{Binding Path=TEST}" Stretch="Uniform" />
(datacontext is set to my ViewModel)
And it still doesn't work and does the weird image modification (pixW, pixH, W and H set to 1)
FINAL UPD:
It seems I finally solved the problem. Here is simply what I did :
byte[] bytes = bin.ReadBytes(imageBytesLenght);
MemoryStream mem = new MemoryStream(bytes);
img = new BitmapImage();
img.BeginInit();
img.StreamSource = mem;
img.EndInit();
the strange thing is that it didn't work the first time, maybe it is due to an architectural modification within my spriteanimation class, but I don't think it is.
Well, thank you a lot to Eugene Cheverda for his help
At the first, I think you should store your images in a list of BitmapSource and provide reverse encoding of image for using stream as BitmapImage.StreamSource:
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
BinaryReader bin = new BinaryReader(fs);
int animCount = bin.ReadInt16();
int imageBytesLenght;
byte[] imageBytes;
List<BitmapSource> bitmaps = new List<BitmapSource>();
for (int i = 0; i < animCount; i++)
{
imageBytesLenght = bin.ReadInt32();
imageBytes = bin.ReadBytes(imageBytesLenght);
bitmaps.Add(getBmpSrcFromBytes(imageBytes));
}
bin.Close();
UPD
In code above use func written below:
private BitmapSource getBmpSrcFromBytes(byte[] bytes)
{
using (var srcStream = new MemoryStream(bytes))
{
var dec = new PngBitmapDecoder(srcStream, BitmapCreateOptions.PreservePixelFormat,
BitmapCacheOption.Default);
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(dec.Frames[0]);
BitmapImage bitmapImage = null;
bool isCreated;
try
{
using (var ms = new MemoryStream())
{
encoder.Save(ms);
bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = ms;
bitmapImage.EndInit();
isCreated = true;
}
}
catch
{
isCreated = false;
}
return isCreated ? bitmapImage : null;
}
}
Hope this helps.
UPD #2
Your binding is incorrect. You may be should bind selected item to for example CurrentImageSource. And then this CurrentImageSource bind to Image control.
Code:
public class MyViewModel : INotifyPropertyChanged
{
public ObservableCollection<BitmapSource> ImagesCollection { get; set; }
private BitmapSource _currentImage;
public BitmapSource CurrentImage
{
get { return _currentImage; }
set
{
_currentImage = value;
raiseOnPropertyChanged("CurrentImage");
}
}
private void raiseOnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
Then:
<ListBox ItemsSource="{Binding ImagesCollection}" SelectedItem="{Binding CurrentImage}"/>
<Image Source="{Binding CurrentImage}"/>
ADDED
Here is the sample project in which implemented technique as I described above.
It creates animations collection and represent them in listbox, selected animation is displayed in Image control using its Image property.
What I want to say is that if you cannot obtain image as it should be, you need to search problems in serialization/deserialization.

Resources