[英]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 表供參考: 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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.