I'm new to WPF and am having some trouble loading an image from a file that has been modified.
I have an image control called Image1, which I load in the following manner
string fileName = "C:\\Users\\..\\myImage.jpg"
BitmapImage tmp = new BitmapImage();
tmp.BeginInit();
tmp.UriSource = new Uri(#fileName, UriKind.Absolute);
tmp.CacheOption = BitmapCacheOption.OnLoad;
tmp.EndInit();
Image1.Source = tmp;
This works the first time, but then I run a function which overwrites myImage.jpg, at which point I call this code again, expecting Image1 to update. However, the GUI remains unchanged. Does it have something to do with the cacheoption? I need that so that I can overwrite the file.
First of all when we want a modified image file,then we have to save first the image
file by calling save method in that function where u r overwriting.
when saving also do something cleverly, like create copy of that original image file then modify that copied file,then save the file,so that when u access again that image file,u can get that modified file + original file.Because sometimes the original file will modified.
Related
I'm making an app that adds (draws) some text on an image stored initially in a file. I managed to modify the image and save it in another file, but I'm trying not to create a second file, but store the result in the original file, although when I try to do that, as said in the Microsoft documentation website, that will result in an Exception being thrown (because the Image.Save method does not allow to write in the same file the image was created from). Is there a way to do it properly?
Right now I've made a workaround, saving the modified image into another file, and then I deleting it and changing the name of the second file to the original one.
Here's my code.
Image image = Image.FromFile(originalFile);
Graphics graphics = Graphics.FromImage(image);
...
graphics.DrawString(line, ...);
...
image.Save(newFile);
graphics.Dispose();
image.Dispose();
File.Delete(originalFile);
File.Move(newFile, originalFile);
The docs for Image.FromFile do say "The file remains locked until the Image is disposed."
Your method is fine (though File.Replace would probably be better than deleting and moving).
If you do want to unlock the file earlier, another option would be to clone the image once it's opened, dispose of the "file-backed" image, and use that image for your drawing.
I have build a program which allows me to insert comment and the title of an Image through System.Image.Drawing so right now, I have trouble trying to overwrite the existing Jpeg file with the one that has comment and title added into it, but I am encountering error while deleting the file, so I'm not sure what to do as I have tried disposing the file but I cant saved it in that case, due to the fact that I disposed it too early, but I cant saved it because the existing file name is not deleted so I'm kinda stuck in the middle right now.
Here are my codes for it:
public string EditComment(string OriginalFilepath, string newFilename)
{
image = System.Drawing.Image.FromFile(OriginalFilepath);
PropertyItem propItem = image.PropertyItems[0];
using (var file = System.Drawing.Image.FromFile(OriginalFilepath))
{
propItem.Id = 0x9286; // this is the id for 'UserComment'
propItem.Type = 2;
propItem.Value = System.Text.Encoding.UTF8.GetBytes("HelloWorld\0");
propItem.Len = propItem.Value.Length;
file.SetPropertyItem(propItem);
PropertyItem propItem1 = file.PropertyItems[file.PropertyItems.Count() - 1];
file.Dispose();
image.Dispose();
string filepath = Filepath;
if (File.Exists(#"C:\Desktop\Metadata"))
{
System.IO.File.Delete(#"C:\Desktop\Metadata");
}
string newFilepath = filepath + newFilename;
file.Save(newFilepath, ImageFormat.Jpeg);//error appears here
return filepath;
}
}
The Error shown are:
An exception of type 'System.ArgumentException' occurred in System.Drawing.dll but was not handled in user code
Additional information: Parameter is not valid.
The problem is that opening an image from file locks the file. You can get around that by reading the file into a byte array, creating a memory stream from that, and then opening the image from that stream:
public string EditComment(string originalFilepath, string newFilename)
{
Byte[] bytes = File.ReadAllBytes(originalFilepath);
using (MemoryStream stream = new MemoryStream(bytes))
using (Bitmap image = new Bitmap(stream))
{
PropertyItem propItem = image.PropertyItems[0];
// Processing code
propItem.Id = 0x9286; // this is the id for 'UserComment'
propItem.Type = 2;
propItem.Value = System.Text.Encoding.UTF8.GetBytes("HelloWorld\0");
propItem.Len = propItem.Value.Length;
image.SetPropertyItem(propItem);
// Not sure where your FilePath comes from but I'm just
// putting it in the same folder with the new name.
String newFilepath;
if (newFilename == null)
newFilepath = originalFilePath;
else
newFilepath = Path.Combine(Path.GetDirectory(originalFilepath), newFilename);
image.Save(newFilepath, ImageFormat.Jpeg);
return newFilepath;
}
}
Make sure you do not dispose your image object inside the using block as you did in your test code. Not only does the using block exist exactly so you don't have to dispose manually, but it's also rather hard to save an image to disk that no longer exists in memory. Similarly, you seem to open the image from file twice. I'm just going to assume all of those were experiments to try to get around the problem, but do make sure to clean those up.
The basic rules to remember when opening images are these:
An Image object created from a file will lock the file during the life cycle of the image object, preventing the file from being overwritten or deleted until the image is disposed.
An Image object created from a stream will need the stream to remain open for the entire life cycle of the image object. Unlike with files, there is nothing actively enforcing this, but after the stream is closed, the image will give errors when saved, cloned or otherwise manipulated.
Contrary to what some people believe, a basic .Clone() call on the image object will not change this behaviour. The cloned object will still keep the reference to the original source.
Note, if you actually want a usable image object that is not contained in a using block, you can use LockBits and Marshal.Copy to copy the byte data of the image object into a new image with the same dimensions and the same PixelFormat, effectively making a full data clone of the original image. (Note: I don't think this works on animated GIF files) After doing that, you can safely dispose the original and just use the new cleanly-cloned version.
There are some other workarounds for actually getting the image out, but most of them I've seen aren't optimal. These are the two most common other valid workarounds for the locking problem:
Create a new Bitmap from an image loaded from file using the Bitmap(Image image) constructor. This new object will not have the link to that file, leaving you free to dispose the one that's locking the file. This works perfectly, but it changes the image's colour depth to 32-bit ARGB, which might not be desired. If you just need to show an image on the UI, this is an excellent solution, though.
Create a MemoryStream as shown in my code, but not in a using block, leaving the stream open as required. Leaving streams open doesn't really seem like a good idea to me. Though some people have said that, since a MemoryStream is just backed by a simple array, and not some external resource, the garbage collector apparently handles this case fine...
I've also seen some people use System.Drawing.ImageConverter to convert from bytes, but I looked into the internals of that process, and what it does is actually identical to the last method here, which leaves a memory stream open.
I've taken over a poorly designed project from a co-worker and am looking to load a picture box directly from the WIA command that just completed to take a picture from an attached USB camera.
The current implementation waits until the file has been written to disk, then displays it from there probably
re-reading the file from disk.
Item item = d.ExecuteCommand(WIA.CommandID.wiaCommandTakePicture);
WIA.ImageFile imagefile = item.Transfer(FormatID.wiaFormatJPEG) as WIA.ImageFile;
I tried casting an Image to the given picture box without success
picBox.Image = (Image)imageFile;
WIA.ImageFile is a COM object wrapper, not a System.Drawing.Image.
You'll have to mess with WIA.ImageFile Save method with temporary files or try in-memory solution as shown here:
http://www.pcreview.co.uk/forums/wia-imagefile-system-drawing-image-t2321026.html
var imageBytes = (byte[])image.FileData.get_BinaryData();
var ms = new MemoryStream(imageBytes);
var img = Image.FromStream(ms);
Good day all,
I am having some trouble with image permissions.
I am loading an image from file, resizing it and then saving it out to another folder.
I am then displaying this like so:
uriSource = new Uri(Combine(imagesDirectoryTemp, generatedFileName), UriKind.Absolute);
imgAsset.Source = new BitmapImage(uriSource);
This is working fine, the trouble comes if the user then selects another image immediately after and tries to save it over the original file.
An exception is generated upon saving my image "ExternalException: A generic error occurred in GDI+."
After some playing around i have narrowed the error down to imgAsset.Source = new BitmapImage(uriSource); as removing this line and not setting the imagesource will allow me to overwrite this file many times.
I have also tried setting the source to something else, before re-saving in the hope that the old reference would be disposed, this was not the case.
How can i get past this error?
Thanks,
Kohan
Edit
Now using this code i am not getting the exception however the image source is not updating. Also since i am not using a SourceStream, im not sure what i need to dispose of to get this working.
uriSource = new Uri(Combine(imagesDirectoryTemp, generatedFileName), UriKind.Absolute);
imgTemp = new BitmapImage();
imgTemp.BeginInit();
imgTemp.CacheOption = BitmapCacheOption.OnLoad;
imgTemp.UriSource = uriSource;
imgTemp.EndInit();
imgAsset.Source = imgTemp;
You're almost there.
Using BitmapCacheOption.OnLoad was the best solution to keep your file from being locked.
To cause it to reread the file every time you also need to add BitmapCreateOptions.IgnoreImageCache.
Adding one line to your code should do it:
imgTemp.CreateOption = BitmapCreateOptions.IgnoreImageCache;
thus resulting in this code:
uriSource = new Uri(Combine(imagesDirectoryTemp, generatedFileName), UriKind.Absolute);
imgTemp = new BitmapImage();
imgTemp.BeginInit();
imgTemp.CacheOption = BitmapCacheOption.OnLoad;
imgTemp.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
imgTemp.UriSource = uriSource;
imgTemp.EndInit();
imgAsset.Source = imgTemp;
When you load an Image in any WPF control it let's handle to your image and doesn't release it until you close your application. The reason for this... I dont know exactly, problably is relaying on some DirectX code behind the scene which never knows when the WPF application releases the image..
Use this code to load the image..
MemoryStream mstream = new MemoryStream();
System.Drawing.Bitmap bitmap = new Bitmap(imgName);
bitmap.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg);
bitmap.Dispose(); // Releases the file.
mstream.Position = 0;
image.BeginInit();
image.StreamSource = mstream;
image.EndInit();
this.img.Source = image ;
it worked for me..
Sounds very much like the problem I had developing Intuipic, where WPF would not dispose of the image, thus locking the file. Check out this converter I wrote to deal with the problem.
I was loading a Bitmap Image from a File. When I tried to save the Image to another file I got the following error "A generic error occurred in GDI+". I believe this is because the file is locked by the image object.
Ok so tried calling the Image.Clone function. This still locks the file.
hmm. Next I try loading a Bitmap Image from a FileStream and load the image into memory so GDI+ doesn't lock the file. This works great except I need to generate thumbnails using Image.GetThumbnailImage method it throws an out of memory exception. Apparently I need to keep the stream open to stop this exception but if I keep the stream open then the file remains locked.
So no good with that method. In the end I created a copy of the file. So now I have 2 versions of the file. 1 I can lock and manipulate in my c# program. This other original file remains unlocked to which I can save modifications to. This has the bonus of allowing me to revert changes even after saving them because I'm manipulating the copy of the file which cant change.
Surely there is a better way of achieving this without having to have 2 versions of the image file. Any ideas?
Well if you're looking for other ways to do what you're asking, I reckon it should work to create a MemoryStream, and read out the FileStream to it, and load the Image from that stream...
var stream = new FileStream("original-image", FileMode.Open);
var bufr = new byte[stream.Length];
stream.Read(bufr, 0, (int)stream.Length);
stream.Dispose();
var memstream = new MemoryStream(bufr);
var image = Image.FromStream(memstream);
Or something prettier to that extent.
Whether or not that's the way you should go about solving that problem, I don't know. :)
I've had a similar problem and wound up fixing it like this.
I have since found an alternative method to clone the image without locking the file. Bob Powell has it all plus more GDI resources.
//open the file
Image i = Image.FromFile(path);
//create temporary
Image t=new Bitmap(i.Width,i.Height);
//get graphics
Graphics g=Graphics.FromImage(t);
//copy original
g.DrawImage(i,0,0);
//close original
i.Dispose();
//Can now save
t.Save(path)
I had a similar problem. But I knew, that I will save the image as a bitmap-file. So I did this:
public void SaveHeightmap(string path)
{
if (File.Exists(path))
{
Bitmap bitmap = new Bitmap(image); //create bitmap from image
image.Dispose(); //delete image, so the file
bitmap.Save(path); //save bitmap
image = (Image) bitmap; //recreate image from bitmap
}
else
//...
}
Sure, thats not the best way, but its working :-)