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))
    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.Save(newFile, ImageFormat.Jpeg); 
Enter fullscreen mode Exit fullscreen mode

Discussion (0)