如何将自定义EXIF标记添加到图像

时间:2016-02-09 15:01:50

标签: c# image metadata exif

我想为图片添加新标签(“LV95_original”)(JPG,PNG或其他东西..)

如何为图片添加自定义EXIF标签?

这是我到目前为止所尝试的:

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

这就是我研究的内容:

Add custom attributes:这使用了不同的东西

SetPropert:这会更新一个属性,我需要添加一个新属性

Add EXIF info:这会更新标准代码

Add new tags:这是我尝试过的,没有用的

1 个答案:

答案 0 :(得分:4)

实际上你正在使用的link工作得很好。但你确实错过了一个重点:

  • 您应该将Id设置为合适的值; 0x9286是' UserComment'当然是一个很好玩的人。

你可以自己制作新的ID,但Exif观众可能不会选择那些......

另外:您应 已知文件中获取有效的PropertyItem!那是你确定它有一个。 或者,如果您确定您的目标文件确实至少有一个PropertyItem,您可以继续使用它作为您要添加的目标文件的投标,但您仍然需要更改其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);
    }
}

有ID to be found from here列表。

请注意,您将需要保存到新文件,因为您仍然保留旧文件。

您可以通过他们的ID进行检索:

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

并得到如下字符串值:

PropertyItem pi = getPropertyItemByID(file, 0x9999);  // ! A fantasy Id for testing!
if (pi != null)
{
    Console.WriteLine( System.Text.Encoding.Default.GetString(pi.Value));
}