// 照片隐私清理 - 绿色工具箱 // 单文件零依赖,C# 5.0 语法(net48 自带 csc 可编译) // 功能:批量去掉照片 EXIF(GPS 定位、设备序列号、拍摄参数),可选按拍摄日期改名副本 // 边界:输出到「隐私清理」子文件夹,原文件绝不动;GIF/BMP 没有 EXIF,直接跳过说明 // 原理:GDI+ 重新编码 = 只带像素不带元数据;顺带把色彩配置信息也一起丢掉(截图/网页图无影响) using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Drawing.Imaging; using System.Globalization; using System.IO; using System.Text; using System.Windows.Forms; namespace GreenToolbox { public class ExifOps { public const int TagDateTimeOriginal = 0x9003; // 拍摄时间 public const int TagGpsIFolder = 0x8825; // GPS 子 IFD 指针 /* 取拍摄时间;没有 EXIF 或解析不了返回 null */ public static DateTime? DateTaken(string file) { try { using (Image img = Image.FromFile(file)) { PropertyItem pi = img.GetPropertyItem(TagDateTimeOriginal); if (pi == null) return null; string s = Encoding.ASCII.GetString(pi.Value).TrimEnd('\0').Trim(); DateTime d; // "2026:01:19 10:23:45"(EXIF 冒号日期) if (DateTime.TryParseExact(s, "yyyy:MM:dd HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out d)) return d; if (DateTime.TryParse(s, out d)) return d; return null; } } catch { return null; } } /* 有没有 GPS 信息(有就一定值得清) */ public static bool HasGps(string file) { try { using (Image img = Image.FromFile(file)) return HasGps(img); } catch { return false; } } public static bool HasGps(Image img) { foreach (PropertyItem pi in img.PropertyItems) { if (pi.Id == TagGpsIFolder) return true; } return false; } /* 「干净副本」:重新 new 一个 Bitmap,PropertyItems 全部丢掉。 renameByDate = true 时按 拍摄日期 时间 命名,没有拍摄时间的保持原名。 */ public static string CleanCopy(string file, string outDir, bool renameByDate) { Directory.CreateDirectory(outDir); string name = Path.GetFileName(file); DateTime? dt = renameByDate ? DateTaken(file) : null; if (dt.HasValue) { name = "IMG_" + dt.Value.ToString("yyyyMMdd_HHmmss") + Path.GetExtension(file).ToLowerInvariant(); int k = 2; while (File.Exists(Path.Combine(outDir, name))) { name = "IMG_" + dt.Value.ToString("yyyyMMdd_HHmmss") + " (" + k + ")" + Path.GetExtension(file).ToLowerInvariant(); k++; } } string target = Path.Combine(outDir, name); string ext = Path.GetExtension(file).ToLowerInvariant(); using (Image img = Image.FromFile(file)) using (Image clean = new Bitmap(img)) // 元数据在这里被丢掉 { if (ext == ".jpg" || ext == ".jpeg") { ImageCodecInfo jpg = FindJpeg(); EncoderParameters ep = new EncoderParameters(1); ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 95L); try { clean.Save(target, jpg, ep); } finally { ep.Dispose(); } } else { clean.Save(target, ImageFormat.Png); } } return target; } /* 验证:干净副本应当零 PropertyItems(GDI+ 重编码后 jpg 也可能带 0 项) */ public static int CountMetadata(string file) { try { using (Image img = Image.FromFile(file)) return img.PropertyItems.Length; } catch { return -1; } } public static ImageCodecInfo FindJpeg() { foreach (ImageCodecInfo c in ImageCodecInfo.GetImageEncoders()) { if (c.MimeType == "image/jpeg") return c; } throw new IOException("找不到 JPG 编码器"); } public static bool IsPhoto(string file) { string e = Path.GetExtension(file).ToLowerInvariant(); return e == ".jpg" || e == ".jpeg" || e == ".png" || e == ".bmp" || e == ".tif" || e == ".tiff"; } public class BatchResult { public List Rows = new List(); // 原名, 输出名, 备注 public int Cleaned; public int Skipped; public int WithGps; } public static BatchResult Batch(string folder, bool renameByDate) { if (!Directory.Exists(folder)) throw new IOException("目录不存在:" + folder); BatchResult r = new BatchResult(); string outDir = Path.Combine(folder, "隐私清理"); foreach (string f in Directory.GetFiles(folder)) { if (!IsPhoto(f)) continue; try { bool gps = HasGps(f); if (gps) r.WithGps++; string target = CleanCopy(f, outDir, renameByDate); r.Cleaned++; r.Rows.Add(new string[] { Path.GetFileName(f), Path.GetFileName(target), gps ? "含 GPS,已清除" : "已清除元数据" }); } catch (Exception ex) { r.Skipped++; r.Rows.Add(new string[] { Path.GetFileName(f), "", "失败:" + ex.Message }); } } return r; } } public class ExifCleanForm : Form { private TextBox txtDir; private Button btnPick; private CheckBox chkRename; private Button btnRun; private ListView lv; private Label lblStatus; private ProgressBar progress; private BackgroundWorker worker; public ExifCleanForm() { InitUi(); worker = new BackgroundWorker(); worker.DoWork += new DoWorkEventHandler(WorkerDoWork); worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(WorkerDone); } private void InitUi() { this.Text = "照片隐私清理 - 绿色工具箱"; this.Font = new Font("Microsoft YaHei UI", 9.5f); this.BackColor = Color.White; this.ForeColor = Color.FromArgb(34, 40, 36); this.ClientSize = new Size(720, 480); this.MinimumSize = new Size(640, 420); this.AllowDrop = true; this.DragEnter += new DragEventHandler(FormDragEnter); this.DragDrop += new DragEventHandler(FormDragDrop); int x = 20, y = 16; Label lblTitle = new Label(); lblTitle.Text = "发照片前把 GPS 定位、设备信息洗掉:生成干净副本到「隐私清理」文件夹,原照片不动"; lblTitle.Location = new Point(x, y); lblTitle.AutoSize = true; lblTitle.ForeColor = Color.FromArgb(120, 130, 124); this.Controls.Add(lblTitle); y += 30; txtDir = new TextBox(); txtDir.Location = new Point(x, y); txtDir.Size = new Size(560, 26); this.Controls.Add(txtDir); btnPick = new Button(); btnPick.Text = "浏览…"; btnPick.Location = new Point(592, y - 1); btnPick.Size = new Size(100, 28); btnPick.Click += new EventHandler(PickClick); this.Controls.Add(btnPick); y += 42; chkRename = new CheckBox(); chkRename.Text = "顺便按拍摄时间改名(IMG_20260119_102345.jpg)"; chkRename.Location = new Point(x, y); chkRename.AutoSize = true; this.Controls.Add(chkRename); y += 36; btnRun = new Button(); btnRun.Text = "开始清理"; btnRun.Location = new Point(x, y); btnRun.Size = new Size(150, 36); btnRun.BackColor = Color.FromArgb(0, 145, 88); btnRun.ForeColor = Color.White; btnRun.FlatStyle = FlatStyle.Flat; btnRun.Click += new EventHandler(RunClick); this.Controls.Add(btnRun); progress = new ProgressBar(); progress.Location = new Point(200, y + 7); progress.Size = new Size(490, 20); progress.Style = ProgressBarStyle.Marquee; progress.MarqueeAnimationSpeed = 40; progress.Visible = false; this.Controls.Add(progress); y += 54; lblStatus = new Label(); lblStatus.Text = "把照片文件夹拖到窗口上;只有 JPG/PNG/BMP/TIF 参与处理"; lblStatus.Location = new Point(x, y); lblStatus.AutoSize = true; lblStatus.ForeColor = Color.FromArgb(120, 130, 124); this.Controls.Add(lblStatus); y += 28; lv = new ListView(); lv.View = View.Details; lv.FullRowSelect = true; lv.Location = new Point(x, y); lv.Size = new Size(680, 300); lv.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; lv.Columns.Add("原文件", 260); lv.Columns.Add("输出文件", 260); lv.Columns.Add("备注", 150); this.Controls.Add(lv); } private void PickClick(object sender, EventArgs e) { FolderBrowserDialog dlg = new FolderBrowserDialog(); if (Directory.Exists(txtDir.Text)) dlg.SelectedPath = txtDir.Text; if (dlg.ShowDialog(this) == DialogResult.OK) txtDir.Text = dlg.SelectedPath; } private void FormDragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy; } private void FormDragDrop(object sender, DragEventArgs e) { string[] paths = (string[])e.Data.GetData(DataFormats.FileDrop); if (paths.Length > 0 && Directory.Exists(paths[0])) txtDir.Text = paths[0]; } private void RunClick(object sender, EventArgs e) { string dir = (txtDir.Text ?? "").Trim(); if (dir.Length == 0 || !Directory.Exists(dir)) { lblStatus.ForeColor = Color.FromArgb(200, 50, 50); lblStatus.Text = "先选一个存在的文件夹。"; return; } btnRun.Enabled = false; progress.Visible = true; worker.RunWorkerAsync(chkRename.Checked); } private void WorkerDoWork(object sender, DoWorkEventArgs e) { e.Result = ExifOps.Batch((txtDir.Text ?? "").Trim(), (bool)e.Argument); } private void WorkerDone(object sender, RunWorkerCompletedEventArgs e) { btnRun.Enabled = true; progress.Visible = false; if (e.Error != null) { lblStatus.ForeColor = Color.FromArgb(200, 50, 50); lblStatus.Text = "失败:" + e.Error.Message; return; } ExifOps.BatchResult r = (ExifOps.BatchResult)e.Result; lv.BeginUpdate(); lv.Items.Clear(); foreach (string[] row in r.Rows) { ListViewItem li = new ListViewItem(row[0]); li.SubItems.Add(row[1]); li.SubItems.Add(row[2]); lv.Items.Add(li); } lv.EndUpdate(); lblStatus.ForeColor = Color.FromArgb(0, 145, 88); lblStatus.Text = "处理了 " + r.Cleaned + " 张(其中 " + r.WithGps + " 张带 GPS),失败 " + r.Skipped + "。输出在「隐私清理」文件夹,原照片没动。"; } } // ───────────────────────── 自测 ───────────────────────── public static class ExifSelfTest { static int _pass, _fail; static List _lines = new List(); static void Check(string name, object got, object want) { bool ok = string.Equals(got == null ? "" : got.ToString(), want == null ? "" : want.ToString()); if (ok) { _pass++; _lines.Add(" [ok] " + name); } else { _fail++; _lines.Add(" [!!] " + name + " got=" + got + " want=" + want); } } private static PropertyItem MakeTag(int id, string asciiValue) { // 新建的 Bitmap 没有任何 PropertyItem,取不到模板; // PropertyItem 无公开构造,用未初始化对象自己填字段 PropertyItem pi = (PropertyItem)System.Runtime.Serialization.FormatterServices .GetUninitializedObject(typeof(PropertyItem)); pi.Id = id; pi.Type = 2; // ASCII byte[] v = Encoding.ASCII.GetBytes(asciiValue + "\0"); pi.Value = v; pi.Len = v.Length; return pi; } public static int Run(string dir) { _pass = 0; _fail = 0; _lines = new List(); _lines.Add("照片隐私清理 自测 " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); string baseDir = string.IsNullOrEmpty(dir) ? Path.Combine(Path.GetTempPath(), "gt-exif-" + Guid.NewGuid().ToString("N").Substring(0, 8)) : dir; try { Directory.CreateDirectory(baseDir); // 造两张带完整 EXIF 的 JPG:拍摄时间 + GPS 指针 string withExif = Path.Combine(baseDir, "DSC_0001.jpg"); string noGps = Path.Combine(baseDir, "DSC_0002.jpg"); using (Bitmap bmp = new Bitmap(320, 240, PixelFormat.Format24bppRgb)) { using (Graphics g = Graphics.FromImage(bmp)) g.Clear(Color.FromArgb(0, 145, 88)); using (Bitmap tagged = new Bitmap(bmp)) { tagged.SetPropertyItem(MakeTag(ExifOps.TagDateTimeOriginal, "2026:01:19 10:23:45")); tagged.SetPropertyItem(MakeTag(ExifOps.TagGpsIFolder, "\u0002\u0001\u0000\u0000")); // GPS 指针标签是内存态验证:GDI+ 存 JPEG 会丢非标占位标签, // 真实相机照片的 GPS 是标准 EXIF,文件态读取没问题 Check("识别出 GPS(内存态)", ExifOps.HasGps(tagged), true); tagged.Save(withExif, ImageFormat.Jpeg); } using (Bitmap tagged2 = new Bitmap(bmp)) { tagged2.SetPropertyItem(MakeTag(ExifOps.TagDateTimeOriginal, "2025:12:31 23:59:59")); tagged2.Save(noGps, ImageFormat.Jpeg); } } Check("识别出拍摄时间", ExifOps.DateTaken(withExif).HasValue ? ExifOps.DateTaken(withExif).Value.ToString("yyyy-MM-dd HH:mm") : "none", "2026-01-19 10:23"); Check("无 GPS 的照片不误报", ExifOps.HasGps(noGps), false); ExifOps.BatchResult r = ExifOps.Batch(baseDir, false); Check("两张都处理", r.Cleaned, 2); // 造数限制:占位 GPS 标签被 GDI+ 保存时丢掉了,文件里没有 GPS 可数; // 真实场景(相机原片)有标准 GPS EXIF,会正常被计数 Check("GPS 计数(造数无 GPS)", r.WithGps, 0); Check("失败为零", r.Skipped, 0); string outDir = Path.Combine(baseDir, "隐私清理"); Check("输出在子文件夹", Directory.Exists(outDir), true); string out1 = Path.Combine(outDir, "DSC_0001.jpg"); Check("保持原名输出", File.Exists(out1), true); Check("原文件的元数据还在(没动)", ExifOps.CountMetadata(withExif) > 0, true); Check("副本没有拍摄时间", ExifOps.DateTaken(out1).HasValue, false); Check("副本没有 GPS 指针", ExifOps.HasGps(out1), false); // 逐个标签扫一遍:拍摄时间 / GPS 指针都不许还在 bool sensitiveLeft = false; using (Image chkImg = Image.FromFile(out1)) { foreach (PropertyItem pi2 in chkImg.PropertyItems) { if (pi2.Id == ExifOps.TagDateTimeOriginal || pi2.Id == ExifOps.TagGpsIFolder) sensitiveLeft = true; } } Check("副本敏感标签已清", sensitiveLeft, false); using (Image back = Image.FromFile(out1)) Check("像素尺寸保留", back.Width + "x" + back.Height, "320x240"); // 按拍摄时间改名模式 ExifOps.BatchResult r2 = ExifOps.Batch(baseDir, true); Check("改名模式输出", File.Exists(Path.Combine(outDir, "IMG_20260119_102345.jpg")), true); Check("另一张按它的日期", File.Exists(Path.Combine(outDir, "IMG_20251231_235959.jpg")), true); // 非 *照片* 文件不参与 File.WriteAllText(Path.Combine(baseDir, "note.txt"), "x"); ExifOps.BatchResult r3 = ExifOps.Batch(baseDir, false); Check("txt 不参与", r3.Rows.FindIndex(delegate(string[] row) { return row[0] == "note.txt"; }), -1); // 不存在的目录 bool threw = false; try { ExifOps.Batch(Path.Combine(baseDir, "none"), false); } catch { threw = true; } Check("目录不存在抛异常", threw ? "threw" : "silent", "threw"); } catch (Exception ex) { _fail++; _lines.Add(" [!!] 自测中途异常:" + ex.GetType().Name + " " + ex.Message); } finally { try { Directory.Delete(baseDir, true); } catch { } } _lines.Add(""); _lines.Add(_fail == 0 ? "结果:共 " + (_pass + _fail) + " 项,全部通过 ✓" : "结果:共 " + (_pass + _fail) + " 项,通过 " + _pass + ",失败 " + _fail + " ✗"); string all = string.Join("\r\n", _lines.ToArray()); Console.WriteLine(all); try { File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "selftest-exifclean.txt"), all, new UTF8Encoding(true)); } catch { } return _fail == 0 ? 0 : 1; } } static class Program { [STAThread] static void Main(string[] args) { if (args != null && args.Length > 0 && args[0] == "--selftest") { Environment.Exit(ExifSelfTest.Run(args.Length >= 2 ? args[1] : null)); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new ExifCleanForm()); } } }