ImageDecode.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. using System;
  2. using System.Runtime.InteropServices;
  3. namespace VideoStatusInspectorCSLib
  4. {
  5. /// <summary>
  6. /// 图像读入时的模式
  7. /// </summary>
  8. public enum EnumImreadMode
  9. {
  10. Unchanged = -1,
  11. Grayscale = 0,
  12. Color = 1,
  13. AnyDepth = 2,
  14. AnyColor = 4,
  15. LoadGdal = 8,
  16. }
  17. /// <summary>
  18. /// 图像信息
  19. /// </summary>
  20. public struct StructImageInfo
  21. {
  22. private int _width;
  23. private int _height;
  24. private EnumColorType _colorType;
  25. private IntPtr _dataPointer;
  26. public int Width
  27. {
  28. get => _width;
  29. set => _width = value;
  30. }
  31. public int Height
  32. {
  33. get => _height;
  34. set => _height = value;
  35. }
  36. public EnumColorType ColorType
  37. {
  38. get => _colorType;
  39. set => _colorType = value;
  40. }
  41. public IntPtr DataPointer
  42. {
  43. get => _dataPointer;
  44. set => _dataPointer = value;
  45. }
  46. public StructImageInfo(int width, int height, EnumColorType colorType, IntPtr dataPointer)
  47. {
  48. _width = width;
  49. _height = height;
  50. _colorType = colorType;
  51. _dataPointer = dataPointer;
  52. }
  53. }
  54. public class ImageDecode
  55. {
  56. [DllImport(@"VideoStatusInspector")]
  57. [return: MarshalAs(UnmanagedType.I1)]
  58. internal static extern bool ImgDataDecode(byte[] srcImData, int srcDataSize, EnumImreadMode imreadMode, ref StructImageInfo imageInfo);
  59. [DllImport(@"VideoStatusInspector")]
  60. internal static extern int GetDecodedImgSize(byte[] srcImData, int srcDataSize, EnumImreadMode imreadMode);
  61. private const EnumImreadMode _imreadMode = EnumImreadMode.Unchanged;
  62. private byte[] _decodedBytes = new byte[0];
  63. private string _errorMsg;
  64. public RawImage DecodeOneImage(byte[] bytes)
  65. {
  66. try
  67. {
  68. var decodedByteCounts = GetDecodedImgSize(bytes, bytes.Length, _imreadMode);
  69. if (_decodedBytes.Length < decodedByteCounts)
  70. {
  71. Array.Resize(ref _decodedBytes, decodedByteCounts);
  72. }
  73. IntPtr dataPointer = Marshal.UnsafeAddrOfPinnedArrayElement(_decodedBytes, 0);
  74. StructImageInfo imageInfo = new StructImageInfo(0, 0, EnumColorType.Bgr, dataPointer);
  75. if (!ImgDataDecode(bytes, bytes.Length, _imreadMode, ref imageInfo))
  76. {
  77. _errorMsg = "Failed at ImgDataDecode.";
  78. return null;
  79. }
  80. return new RawImage(_decodedBytes, imageInfo.Width, imageInfo.Height, imageInfo.ColorType);
  81. }
  82. catch (Exception excep)
  83. {
  84. _errorMsg = "Failed at DecodeOneImage: "+ excep.Message;
  85. return null;
  86. }
  87. }
  88. public string GetErrorMsg()
  89. {
  90. return _errorMsg;
  91. }
  92. }
  93. }