DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Joe Enos
Joe Enos

Posted on

Add EXIF date with .NET

EXIF is an absurdly large specification for digital photos. 99 times out of 100, all I care about in a photo is the date taken, and even that isn't simple.

.NET doesn't let you easily manipulate it, but here's a way that I've found. No promises that this will always work or that it's the correct way of doing things, but it does seem to function for me.

using var image = Image.FromFile(oldFile);
foreach (int propertyID in new[] { 0x9003, 0x9004, 0x0132 })
{
    if (image.PropertyIdList.Contains(propertyID))
    {
        image.RemovePropertyItem(propertyID);
    }
    PropertyItem propertyItem;

    // No public constructor, but it's a simple data type, so we'll cheat and use reflection
    propertyItem = (PropertyItem)typeof(PropertyItem).Assembly.CreateInstance(typeof(PropertyItem).FullName,
        ignoreCase: false,
        bindingAttr: BindingFlags.Instance | BindingFlags.NonPublic,
        binder: null,
        args: null,
        culture: null,
        activationAttributes: null);

    propertyItem.Id = propertyID;
    propertyItem.Len = 20;
    propertyItem.Type = 2;
    Console.WriteLine("Creating new property");
    // }

    propertyItem.Value = Encoding.UTF8.GetBytes(theDate.ToString("yyyy\\:MM\\:dd HH\\:mm\\:ss") + "\0");
    image.SetPropertyItem(propertyItem);
}

image.Save(newFile, ImageFormat.Jpeg); 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

🌚 Browsing with dark mode makes you a better developer.

It's a scientific fact.