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

本文关键字:自定义 EXIF 标记 添加 图像 | 更新日期: 2023-09-27 18:33:48

我想为图像添加一个新标签("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);
}

这是我研究的:

添加自定义属性:这会使用不同的属性

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

添加 EXIF 信息:这将更新标准标记

添加新标签:这是我尝试过的,没有奏效

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

实际上,您使用的链接工作正常。然而,你确实错过了一个重要的点:

  • 您应该将Id设置为合适的值; 0x9286是"用户评论",当然是一个很好的玩法。

您可以自己制作新的ID,但Exif观众可能不会选择这些ID。

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

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

您可以通过他们的 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));
}