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

min*_*men 5 c# exif metadata image

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

这就是我研究的内容:

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

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

添加EXIF信息:这会更新标准标签

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

TaW*_*TaW 5

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

  • 您应该将设置Id为合适的值;0x9286是“ UserComment”,肯定是一个不错的选择。

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

另外:你应该要么抓住有效的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);
    }
}
Run Code Online (Sandbox Code Playgroud)

从此处可以找到 ID列表。

请注意,由于仍要保留旧文件,因此需要保存到新文件。

您可以通过其ID进行检索:

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

并得到这样的字符串值:

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

  • System.Drawing.Image类型将接受并与任何图像类型一起使用,但是当`Save()`图像时,它仅适用于JPG。 (2认同)