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



我正在使用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 表: https://msdn.microsoft.com/en-us/library/system.drawing.imaging.propertyitem.id(v=vs.110(.aspx

0x0112- 方向

0x0132- 日期/时间

我终于想出了如何删除所有不需要的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;
}

最新更新