Creating BitmapImage throws missing key exception - wpf

I have a view that displays an image with it's title and comment alongside it.
When I load up existing images I utilize this code:
this.ArtifactIdentity = image.ArtifactIdentity;
this.Comment = image.Comment;
this.Name = image.Name;
this.MediaIdentity = image.MediaIdentity;
this.ImageArray = image.Image;
Image = new BitmapImage();
Image.BeginInit();
Image.CacheOption = BitmapCacheOption.None;
Image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
Image.StreamSource = new MemoryStream(this.ImageArray);
Image.EndInit();
When I execute the EndInit() it throw the exception missing parameter key. The stack trace shows this:
at System.Collections.Hashtable.ContainsKey(Object key)
at System.Collections.Hashtable.Contains(Object key)
at System.Windows.Media.Imaging.ImagingCache.RemoveFromCache(Uri uri, Hashtable table)
at System.Windows.Media.Imaging.BitmapImage.FinalizeCreation()
at System.Windows.Media.Imaging.BitmapImage.EndInit()
So can anyone tell me why I am getting this exception when I am using code I've seen many others use with success and yet I get this exception??? I'm at a loss!

This is caused by a bug in WPF, in BitmapImage.FinalizeCreation():
if ((CreateOptions & BitmapCreateOptions.IgnoreImageCache) != 0)
{
ImagingCache.RemoveFromImageCache(uri);
}
If you specify IgnoreImageCache, but don't load from a URI, it breaks.
Just get rid of that flag; it only applies when loading from URLs.

I found an article that was written by Bradley Grainger here and had a list of exceptions caused by loading a BitmapImage. What SLaks stated is correct but in Brad's article he stated that the next exception (No Imaging component suitable to complete...) is frequently showing up on Windows 7 machines. The exception suggests that the metadata is corrupted in some way.
My solution took some testing to confirm but basically if I take the byte stream, save it to a temp file, then use that tempfile to populate the BitmapImage I can successfully load it without exceptions.
It is not the most desired solution but it does the one thing that I needed: it displays the image without exceptions!

Related

TallComponents.PDF.Document Error: "the document is corrupt, rebuilding failed"

I'm getting exception "the document is corrupt, rebuilding failed",
while instantiating TallComponents.PDF.Document from MemoryStream.
The byteResponse is good. that is, the document is NOT Corrupted.
However, I am running this method in loop to create multiple PDFs.
Am I missing something? Do I need to make any additional checks?
using (Stream stream = new MemoryStream(byteResponse, true))
{
var pdf = new TallComponents.PDF.Document(stream);
Please set stream.Position = 0; before creating the instance of Tall Pdf.
You are doing it but after the instance has been created.

still memory-leaks in .net4 - binding memory BitmapImage to Image-Source

I know very similar questions were asked here in the past - but neither had a solution for my problem:
I load a image from memory into a BitmapImage:
private static BitmapImage LoadImage(byte[] imageData)
{
if (imageData == null || imageData.Length == 0) return null;
var image = new BitmapImage();
using (var mem = new MemoryStream(imageData))
{
mem.Position = 0;
image.BeginInit();
image.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
image.CacheOption = BitmapCacheOption.OnLoad;
image.UriSource = null;
image.StreamSource = mem;
image.EndInit();
}
image.Freeze();
return image;
}
And then use this (with INotifyPropertyChange) to bind the resulting BitmapImage to the Source of a Image object (on a Page).
Problem is: this will leak memory (a lot in my case up to 300MB on 2-3 images!)
You don't even find this using Profilers - only the .net Memory Profiler got me on track (as it's in unmanaged memory where all the bytes go - so ANTS tell me ".NET is using 19,24MB of 367,3MB total private bytes allocated to the application" - nice):
No matter what I try - I don't get this leak away.
Tried (single and all at once):
clear the Visual-Tree / remove the Image on Unload
Set the Image-Source to null
use ImageBrush in Rectangle instead of Image
other CacheOptions without Disposing the MemoryStream
don't Freeze the Image
I don't get this - really!
As soon as I stop using the Image in the Source everything is ok (no leak).
Someone any options I can try?
REMARK
Seems like this is no bug at all (see my second comment) - I have to check this so I will let the question open for now - maybe this can help with the other questions on this as well
Sorry guys - this was indeed no "BUG" but caused by high-resolution pictures.
Please comment on this if I should delete the question or if I should leave it here as other people might come into the same situation...

Continual (rapid) update of WPF Image

There is a website that contains a single image from a webcam. Each time the site is hit, the most current image of the webcam is displayed. I want to make a real time video by hitting the site continuously.
I have searched and tried several things but cannot get it to refresh at a reasonable rate.
public MainWindow()
{
InitializeComponent();
this.picUri = "http://someurl";
this.thWatchVideo = new Thread(new ThreadStart(Watch));
_image = new BitmapImage();
_image.BeginInit();
_image.CacheOption = BitmapCacheOption.None;
_image.UriCachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
_image.CacheOption = BitmapCacheOption.OnLoad;
_image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
_image.UriSource = new Uri(this.picUri);
_image.EndInit();
this.imgVideo.Source = _image;
this.thWatchVideo.Start();
}
public void Watch()
{
while(true)
{
UpdateImage();
}
}
public void UpdateImage()
{
if (this.imgVideo.Dispatcher.CheckAccess())
{
_image = new BitmapImage();
_image.BeginInit();
_image.CacheOption = BitmapCacheOption.None;
_image.UriCachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
_image.CacheOption = BitmapCacheOption.OnLoad;
_image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
_image.UriSource = new Uri(this.picUri);
_image.EndInit();
this.imgVideo.Source = _image;
}
else
{
UpdateImageCallback del = new UpdateImageCallback(UpdateImage);
this.imgVideo.Dispatcher.Invoke(del);
}
}
Problem is, this is too slow and takes too long to refresh and the app just hangs.
I got this to work in Windows Forms with the PictureBox control but cannot get it to work in WPF. I refuse to believe that WPF is inferior to forms.
This app will always just hang (whether winforms or WPF) because you've got an infinite loop running everything it does on the UI thread. Your app hangs because you're not allowing the UI thread any time to process user input (such as resizing the window or trying to close the app).
With regard to your performance: have you tried profiling your code? I suspect that the problem is to do with you repeatedly hammering a webserver for an image, since you're never likely to get enough requests-per-second to make any kind of real-time video from static images. (There's a reason that we have video streaming codecs!)
instead of recreating whole image try to change only UriSource property.
Check out my answer to this: Showing processed images from an IP camera
Also, make sure the communication is done on a separate thread.
I suggest that the Bitmap image is a dependency object being created on a non-GUI thread. You then invoke UpdateImage on the GUI thread. Since the bitmap image dependency object wasn't created on/(owned by) the GUI thread, you get the "different thread owns it" error.
How about this as a workaround?
Copy the image temporarily to a local file location in your Watch routine.
Add a Thread.Sleep to the watch routine so that you don't hammer the CPU with the endless loop on this thread.
Use BeginInvoke instead of Invoke.
Load and update the image in the UpdateImage routine so that the image and the imgVideo objects are on the GUI thread. Update the image by reading it from your local file copy.
Without knowing the specifics of how you make Watch run on its own thread (using Background worker?) I think this approach will work for you.

loading pictures from a folder on loading time

hello i am trying to load images from files in the start of my program and for some unknown reason
whenever i use those lines somehow i am getting thrown out of my loading function
when i press on a button not during the load of the program it does work and i am able to load pictures
this is my loading pictures code :
Image pic = new Image();
string imagePath = String.Format(#"Images\{0}", 1); // this is ofc a file which is inside my debug
pic.Source = new BitmapImage(new Uri(imagePath)); // folder
more info: when i am trying to put this line in my constructor i am getting for some reason an exception:
A first chance exception of type 'System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll
Additional information: 'The invocation of the constructor on type 'yad2.PresentationLayer.MainWindow' that matches the specified binding constraints threw an exception.' Line number '5' and line position '9'.
thanks in advance for your help
"Images\1" is not a valid URI. You can create the Uri by using the FileInfo class:
FileInfo fi = new FileInfo(imagePath);
Uri uri = new Uri(fi.FullName);
pic.Source = new BitmapImage(uri);
Also, a tip to help you debug exceptions in code-behind: Open the Exceptions window (ctrl+alt+e) and check both boxes for Common Language Runtime Exceptions. This will cause execution to break when the error occurs, making it a lot easier to work out what the problem is.

Windows Phone 7 App Quits when I attempt to deserialize JSON

I'm developing my first windows phone 7 app, and I've hit a snag. basically it's just reading a json string of events and binding that to a list (using the list app starting point)
public void Load()
{
// form the URI
UriBuilder uri = new UriBuilder("http://mysite.com/events.json");
WebClient proxy = new WebClient();
proxy.OpenReadCompleted += new OpenReadCompletedEventHandler(OnReadCompleted);
proxy.OpenReadAsync(uri.Uri);
}
void OnReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null)
{
var serializer = new DataContractJsonSerializer(typeof(EventList));
var events = (EventList)serializer.ReadObject(e.Result);
foreach (var ev in events)
{
Items.Add(ev);
}
}
}
public ObservableCollection<EventDetails> Items { get; private set; }
EventDetails is my class that wraps the json string. this class has to be correct because it is an exact copy of the class used by that website internally from which the json is generated...
I get the json string correctly from the webclient call (I read the memorystream and the json is indeed there) but as soon as I attempt to deserialize the string, the application exits and the debugger stops.
I get no error message or any indication that anything happen, it just stops. This happens if I type the deserialize method into the watch window as well...
I have already tried using JSON.net in fact I thought maybe it was a problem with JSON.net so I converted it to use the native deserializer in the .net framework but the error is the same either way.
why would the application just quit? shouldn't it give me SOME kind of error message?
what could I be doing wrong?
many thanks!
Firstly, the fact that you have some string there that looks like JSON does not mean that you have a valid JSON. Try converting a simple one.
If your JSON is valid, it might be that your JSON implementation does not know how to convert a list to EventList. Give it a try with ArrayList instead and let me know.
The application closes because an unhandled exception happens. If check the App.xaml.cs file you will find the code that closes your app. What you need to do is try catch your deserialization process and handle it locally. So most likely you have some JSON the DataContractJsonSerializer does not like. I have been having issue with it deserializing WCF JSON and have had to go other routes.
You may want to check to ensure your JSON is valid, just because your website likes it does not mean it is actually valid, the code on your site may be helping to correct the issue. Drop a copy of your JSON object (the string) in http://jsonlint.com/ to see if it is valid or not. Crokford (the guy who created JSON) wrote this site to validate JSON, so I would rely on it more than your site ;) This little site has really helped me out of some issues over the past year.
I ran into this same kind of problem when trying to migrate some existing WM code to run on WP7. I believe that the WP7 app crashes whenever it loads an assembly (or class?) that references something that's not available in WP7. In my case, I think it was Assembly.Load or something in the System.IO namespace, related to file access via paths.
While your case might be something completely different, the symptoms were exactly the same.
The only thing I can recommend is to go through the JSON library and see if it's referencing base classes that are not allowed in WP7. Note that it doesn't even have to hit the line of code that's causing the issue - it'll crash as soon as it tries to hit the class that contains the bad reference.
If you can step into the JSON library, you can get a better idea of which class is causing the problem, because as soon as the code references it, the whole app will crash and the debugger will stop.

Resources