Already a little while ago Robert postet some example code on how add meta data to images using the relatively new WPF.

After playing around with the code for a while, I got some weird exceptions thrown at me, e.g. “A first chance exception of type ‘System.Runtime.InteropServices.COMException’ occurred in PresentationCore.dll“. Now, the only thing I had changed was letting the tagging routine run in a seperate thread:

[STAThread]
static void Main()
{
Thread t = new Thread(writeMetadata);
t.Start();
Application.Run(new Form1());
}
static void writeMetadata()
{
// write the metadata to the image here
}

After searching the web for a while I found an article by Aaron who had run into similar problems. Apparently, WPF components cause some trouble when they’re executed outside a thread that doesn’t have its apartment state set to STA. Fortunately, Robert was kind enough to point me in the right direction. All you have to do is set the apartment state right and off you go with WPF components all over your threads :-) Thus, the Main() routine from above changes as follows:

[STAThread]
static void Main()
{
Thread t = new Thread(writeMetadata);
t.SetApartmentState(ApartmentState.STA);
t.Start();
Application.Run(new Form1());
}

That’s all there is to it!

Tags: , , , , , , ,

2 Responses to “Adding metadata (exif, iptc, xmp, etc.) to your image using .NET and the WPF”

wow!

thx for your efforts,
but even if I try to spawn a new thread (inside a webservice), I’ll get the ComException.

Ralf

Hi Ralf,

did you make sure you’re spawning an STAThread? This line is important:

t.SetApartmentState(ApartmentState.STA);

 Feed for this Entry

Something to say?