Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add custom EXIF tags to a image

I'd like to add a new tag ("LV95_original") to an image ( JPG, PNG or something else..)

How can I add a custom EXIF tag to a image?

This is what I've tried so far:

using (var file = Image.FromFile(path))
{
    PropertyItem propItem = file.PropertyItems[0];
    propItem.Type = 2;
    propItem.Value = System.Text.Encoding.UTF8.GetBytes(item.ToString() + "\0");
    propItem.Len = propItem.Value.Length;
    file.SetPropertyItem(propItem);
}

This is what I've researched:

Add custom attributes: This uses something different

SetPropert: This updates a property, I need to add a new one

Add EXIF info: This updates standard tags

Add new tags: This is what I've tried, didn work

like image 441
minimen Avatar asked Feb 09 '16 15:02

minimen


1 Answers

Actually the link you are using is working just fine. You did however miss one important point:

  • You should set the Id to a suitable value; 0x9286 is 'UserComment' and certainly a good one to play with.

You can make up new Ids of your own but Exif viewers may not pick those up..

Also: You should either grab a valid PropertyItem from a known file! That is one you are sure that it has one. Or, if you are sure your target file does have ar least one PropertyItem you can go ahead and use it as a proptotype for the one you want to add, but you still need to change its Id.


public Form1()
{
    InitializeComponent();
    img0 = Image.FromFile(aDummyFileWithPropertyIDs);
}

Image img0 = null;

private void button1_Click(object sender, EventArgs e)
{
    PropertyItem propItem = img0.PropertyItems[0];
    using (var file = Image.FromFile(yourTargetFile))
    {
        propItem.Id = 0x9286;  // this is called 'UserComment'
        propItem.Type = 2;
        propItem.Value = System.Text.Encoding.UTF8.GetBytes(textBox1.Text + "\0");
        propItem.Len = propItem.Value.Length;
        file.SetPropertyItem(propItem);
        // now let's see if it is there: 
        PropertyItem propItem1 = file.PropertyItems[file.PropertyItems.Count()-1];
        file.Save(newFileName);
    }
}

There is are lists of IDs to be found from here.

Note that you will need to save to a new file since you are still holding onto the old one..

You can retrieve by their ID:

PropertyItem getPropertyItemByID(Image img, int Id)
{
    return img.PropertyItems.Select(x => x).FirstOrDefault(x => x.Id == Id);
}

and get at string values like this:

PropertyItem pi = getPropertyItemByID(file, 0x9999);  // ! A fantasy Id for testing!
if (pi != null)
{
    Console.WriteLine( System.Text.Encoding.Default.GetString(pi.Value));
}
like image 99
TaW Avatar answered Oct 21 '22 03:10

TaW