使用 C# 删除 jpeg 图像的 EXIF 数据中除两个字段外的所有字段

Remove all but two fields in EXIF data of a jpeg image using C#

我正在使用 C# 和 ImageFactory 库(来自 ImageProcessor.org)大幅修改 jpg 图像。它可以拉直、裁剪、阴影细节增强等。

它完全正常工作并成功将新图像写入文件。 但此文件包含原始 EXIF 数据,其中大部分现在不正确或无关。

我确实需要在 EXIF 数据中保留方向标志,因为它需要正确定位修改后的图像。我想保留日期时间。但是所有其他 EXIF 数据都应该消失。

我可以找到在图像元数据中添加或修改 EXIF 属性项的方法,但无法删除一个。

     using (ImageFactory ifact = new ImageFactory()) {
        ifact.PreserveExifData = true;
        ifact.Load(edat.ImageFilename);

        // save the image in a bitmap that will be manipulated
        //ifact.PreserveExifData = false;  // tried this but b1 still had EXIF data
        Bitmap b1 = (Bitmap)ifact.Image;

        //lots of processsing here...

        // write the image to the output file
        b1.Save(outfilename, ImageFormat.Jpeg);
      }

这个怎么样:

Bitmap bmp = new Bitmap("C:\Test\test.jpg");

foreach (System.Drawing.Imaging.PropertyItem item in bmp.PropertyItems)
{
    if (item.Id == 0x0112 || item.Id == 0x0132)
        continue;

    System.Drawing.Imaging.PropertyItem modItem = item;
    modItem.Value = new byte[]{0};
    bmp.SetPropertyItem(modItem);
}

bmp.Save("C:\Test\noexif.jpg");

这里是 Id table 以供参考: https://msdn.microsoft.com/en-us/library/system.drawing.imaging.propertyitem.id(v=vs.110).aspx

0x0112 - 方向

0x0132 - Date/Time

我终于想出了如何删除 所有 不需要的 EXIF 标签。

剩下的也可以修改。

  // remove unneeded EXIF data
  using (ImageFactory ifact = new ImageFactory()) {
    ifact.PreserveExifData = true;
    ifact.Load(ImageFilename);
    // IDs to keep: model, orientation, DateTime, DateTimeOriginal
    List<int> PropIDs = new List<int>(new int[] { 272, 274, 306, 36867 });
    // get the property items from the image
    ConcurrentDictionary<int, PropertyItem> EXIF_Dict = ifact.ExifPropertyItems;
    List<int> foundList = new List<int>();
    foreach (KeyValuePair<int, PropertyItem> kvp in EXIF_Dict) foundList.Add(kvp.Key);
    // remove EXIF tags unless they are in the PropIDs list
    foreach (int id in foundList) {
      PropertyItem junk;
      if (!PropIDs.Contains(id)) {
        // the following line removes a tag
        EXIF_Dict.TryRemove(id, out junk);
      }
    }
    // change the retained tag's values here if desired
    EXIF_Dict[274].Value[0] = 1;
    // save the property items back to the image
    ifact.ExifPropertyItems = EXIF_Dict;
  }

我用 RemovePropertyItem 而不是 SetPropertyItem 是这样的:

private Image RemoveGpsExifInfo(Image image)
{
  foreach (var item in image.PropertyItems)
  {
    // GPS range is from 0x0000 to 0x001F. Full list here -> https://exiftool.org/TagNames/EXIF.html (click on GPS tags)
    if (item.Id <= 0x001F)
    {
      image.RemovePropertyItem(item.Id);
    }
  }

  return image;
}