修改元数据后保存图像

时间:2014-01-02 21:39:58

标签: c# image

在修改元数据后保存图像时出现问题。 基本上,我想打开我的图像,显​​示它,修改它的EXIF元数据,然后保存它。

首先,我在尝试保存图像时遇到问题,因为原始文件被锁定(我有一个通用的GTI +错误)。在阅读了一些帖子并找到问题后,我用using关键字解决了锁定问题。

但问题是,如果我使用“using”,我的Image的propertyItems列表为空,我无法修改我的元数据。

以下是我加载图片的方式(使用不同的测试)

this.image = new Bitmap(this.path);         // this cause lock on file

/* the following doesn't lock the file, but image.propertyItems is empty */

//using (var bmpTemp = new Bitmap(this.path))
//{
//    this.image = new Bitmap(bmpTemp);
//}

使用streamReader或MemoryStream无济于事......

以下是我修改和保存图片的方法:

 PropertyItem p = this.photo.Image.GetPropertyItem(0x5090);

 p.Id = 0x320;
 p.Type = 2; // Type ASCII
 p.Len = boxTitle.Text.Length;
 p.Value = Encoding.ASCII.GetBytes(boxTitle.Text);

 this.photo.Image.SetPropertyItem(p);
 this.photo.Image.Save(this.photo.Path);

你能解释一下为什么当我使用“使用”时没有propertyItems,我该如何修改图像元数据而不是保存它?

2 个答案:

答案 0 :(得分:1)

您必须在阅读后单独保留原始图像,修改属性值,然后将其另存为新图像。显然,Microsoft没有在内存中复制元数据 - 只有更改。因此原始图像保持锁定以保留原始元数据。要修改图像的元数据,请保存新图像,然后用它替换旧图像(或删除并重命名)。

答案 1 :(得分:1)

似乎Bitmap构造函数不复制PropertyItems。您可以在图像之间复制PropertyItems,然后释放文件:

using (var bmpTemp = new Bitmap(this.path))
{
    this.image = new Bitmap(bmpTemp);
    foreach (var pi in bmpTemp.PropertyItems)
    {
        this.image.SetPropertyItem(pi);
    }
}

这似乎比复制文件更好。

相关问题