using System; using System.Runtime.InteropServices; namespace VideoStatusInspectorCSLib { /// /// 图像读入时的模式 /// public enum EnumImreadMode { Unchanged = -1, Grayscale = 0, Color = 1, AnyDepth = 2, AnyColor = 4, LoadGdal = 8, } /// /// 图像信息 /// public struct StructImageInfo { private int _width; private int _height; private EnumColorType _colorType; private IntPtr _dataPointer; public int Width { get => _width; set => _width = value; } public int Height { get => _height; set => _height = value; } public EnumColorType ColorType { get => _colorType; set => _colorType = value; } public IntPtr DataPointer { get => _dataPointer; set => _dataPointer = value; } public StructImageInfo(int width, int height, EnumColorType colorType, IntPtr dataPointer) { _width = width; _height = height; _colorType = colorType; _dataPointer = dataPointer; } } public class ImageDecode { [DllImport(@"VideoStatusInspector")] [return: MarshalAs(UnmanagedType.I1)] internal static extern bool ImgDataDecode(byte[] srcImData, int srcDataSize, EnumImreadMode imreadMode, ref StructImageInfo imageInfo); [DllImport(@"VideoStatusInspector")] internal static extern int GetDecodedImgSize(byte[] srcImData, int srcDataSize, EnumImreadMode imreadMode); private const EnumImreadMode _imreadMode = EnumImreadMode.Unchanged; private byte[] _decodedBytes = new byte[0]; private string _errorMsg; public RawImage DecodeOneImage(byte[] bytes) { try { var decodedByteCounts = GetDecodedImgSize(bytes, bytes.Length, _imreadMode); if (_decodedBytes.Length < decodedByteCounts) { Array.Resize(ref _decodedBytes, decodedByteCounts); } IntPtr dataPointer = Marshal.UnsafeAddrOfPinnedArrayElement(_decodedBytes, 0); StructImageInfo imageInfo = new StructImageInfo(0, 0, EnumColorType.Bgr, dataPointer); if (!ImgDataDecode(bytes, bytes.Length, _imreadMode, ref imageInfo)) { _errorMsg = "Failed at ImgDataDecode."; return null; } return new RawImage(_decodedBytes, imageInfo.Width, imageInfo.Height, imageInfo.ColorType); } catch (Exception excep) { _errorMsg = "Failed at DecodeOneImage: "+ excep.Message; return null; } } public string GetErrorMsg() { return _errorMsg; } } }