Wednesday, January 25, 2012 12:49 PM
As documented here on MSDN the PropertyItem object does not have a public constructor.
What to do then when you want to add a property to an image, using Image.SetPropertyItem(..) method?
This post suggests you create some bank of all property items you want, hold it memory and clone from it.
A commenter on that blog suggested using reflection: Get the non-public parameter-less constructor and invoke it. Notable downside for this approach is reliance on internal implementation of the object. True. I'll risk it though.
In my implementation, I added a helper method which simply generates the PropertyItem using System.Activator like so:
public static PropertyItem CreatePropertyItem(int id, int length, short exifType, byte buffer)
var instance = (PropertyItem)Activator.CreateInstance(typeof(PropertyItem), true);
instance.Id = id;
instance.Len = length;
instance.Type = exifType;
instance.Value = buffer;
Pretty clean and simple. Under the covers, Activator will use some reflection to create the instance, but would also utilize some caching and speed written by not-me. I like not-me code because it means I don't have to write it.
Since one of my my upcoming talks at http://socalcodecamp.com is on the subject of reflection, this all falls neatly into place.