ExifHelper.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. //############################################################
  2. // https://github.com/yuzhengyang
  3. // author:yuzhengyang
  4. //############################################################
  5. using System;
  6. using System.Drawing;
  7. using System.Text;
  8. namespace Azylee.Core.IOUtils.ImageUtils
  9. {
  10. public class ExifHelper : IDisposable
  11. {
  12. private Bitmap Image;
  13. private Encoding Encoding = Encoding.UTF8;
  14. private string DefaultValue = "";
  15. public ExifHelper(string fileName)
  16. {
  17. Image = (Bitmap)Bitmap.FromFile(fileName);
  18. }
  19. public ExifHelper(string fileName, string defaultValue)
  20. {
  21. Image = (Bitmap)Bitmap.FromFile(fileName);
  22. DefaultValue = defaultValue;
  23. }
  24. public string GetPropertyString(Int32 pid)
  25. {
  26. if (IsPropertyDefined(pid))
  27. return GetString(Image.GetPropertyItem(pid).Value);
  28. else
  29. return DefaultValue;
  30. }
  31. public double GetPropertyDouble(Int32 pid)
  32. {
  33. double result = 0;
  34. if (IsPropertyDefined(pid))
  35. {
  36. byte[] value = Image.GetPropertyItem(pid).Value;
  37. if (value.Length == 24)
  38. {
  39. double d = BitConverter.ToUInt32(value, 0) * 1.0d / BitConverter.ToUInt32(value, 4);
  40. double m = BitConverter.ToUInt32(value, 8) * 1.0d / BitConverter.ToUInt32(value, 12);
  41. double s = BitConverter.ToUInt32(value, 16) * 1.0d / BitConverter.ToUInt32(value, 20);
  42. result = (((s / 60 + m) / 60) + d);
  43. }
  44. }
  45. return result;
  46. }
  47. public char GetPropertyChar(Int32 pid)
  48. {
  49. char result = ' ';
  50. if (IsPropertyDefined(pid))
  51. {
  52. byte[] value = Image.GetPropertyItem(pid).Value;
  53. result = BitConverter.ToChar(value, 0);
  54. }
  55. return result;
  56. }
  57. private string GetString(byte[] bt)
  58. {
  59. string result = Encoding.GetString(bt);
  60. if (result.EndsWith("\0"))
  61. result = result.Substring(0, result.Length - 1);
  62. return result;
  63. }
  64. private bool IsPropertyDefined(Int32 pid)
  65. {
  66. return (Array.IndexOf(Image.PropertyIdList, pid) > -1);
  67. }
  68. public void Dispose()
  69. {
  70. Image.Dispose();
  71. }
  72. }
  73. }