How to add custom EXIF tags to a image

白昼怎懂夜的黑 提交于 2019-12-07 05:06:38

问题


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


回答1:


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));
}


来源:https://stackoverflow.com/questions/35295284/how-to-add-custom-exif-tags-to-a-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!