123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853 |
- using System.Windows;
- using Accord.Video.FFMPEG;
- using System.Threading;
- using Microsoft.Win32;
- using System.Collections.Generic;
- using System.Threading.Tasks;
- using System;
- using System.Drawing;
- using System.Windows.Media.Imaging;
- using System.Drawing.Imaging;
- using System.Runtime.InteropServices;
- using VideoStatusInspectorCSLib;
- using System.Windows.Forms;
- using System.IO;
- using MessageBox = System.Windows.MessageBox;
- namespace ReadVideoDemo
- {
- /// <summary>
- /// MainWindow.xaml 的交互逻辑
- /// </summary>
- public partial class MainWindow : Window
- {
- [DllImport("kernel32.dll", EntryPoint = "CopyMemory", SetLastError = false)]
- public static extern void CopyMemory(IntPtr dest, IntPtr src, uint count);
- private Queue<string> _videoReadyForTest1 = new Queue<string>();
- private VideoFileReader _reader1 = null;
- private readonly object _locker1 = new object();
- private ManualResetEvent _readEvent1 = new ManualResetEvent(false);
- private VideoStatusInspect _detect1 = new VideoStatusInspect();
- private Queue<string> _imagesReadyForTest1 = new Queue<string>();
- private int _imageCount = 0;
- private Queue<string> _videoReadyForTest2 = new Queue<string>();
- private VideoFileReader _reader2 = null;
- private readonly object _locker2 = new object();
- private ManualResetEvent _readEvent2 = new ManualResetEvent(false);
- private VideoStatusInspect _detect2 = new VideoStatusInspect();
- bool _useIntptrImage = true;
- #region 界面响应
- public MainWindow()
- {
- InitializeComponent();
- _detect1.SetWorkingStateDelayFrames(90);
- _detect2.SetWorkingStateDelayFrames(90);
- #if ENABLE_RAWIMAGE_SAVE
- _detect1.EnableDebugImagesWrite(true);
- _detect2.EnableDebugImagesWrite(true);
- #endif
- }
- /// <summary>
- /// 用户点击了加载视频按钮
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void OnLoadVideo1Click(object sender, RoutedEventArgs e)
- {
- if (_videoReadyForTest1.Count > 0 || _imagesReadyForTest1.Count > 0)
- {
- _videoReadyForTest1.Clear();
- _imagesReadyForTest1.Clear();
- }
- StopVideoReading1();
- Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();
- openFileDialog.Filter = "视频文件|*.mp4;*.avi";
- openFileDialog.Multiselect = true;
- openFileDialog.Title = "选择一个或多个视频";
- if (openFileDialog.ShowDialog() ?? false)
- {
- foreach (string filename in openFileDialog.FileNames)
- {
- _videoReadyForTest1.Enqueue(filename);
- }
- DoVideoReading1();
- }
- }
- /// <summary>
- /// 用户点击了加载图像按钮
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void OnLoadImagesClick(object sender, RoutedEventArgs e)
- {
- if (_videoReadyForTest1.Count > 0 || _imagesReadyForTest1.Count > 0)
- {
- _videoReadyForTest1.Clear();
- _imagesReadyForTest1.Clear();
- }
- StopVideoReading1();
- System.Windows.Forms.FolderBrowserDialog dlg = new System.Windows.Forms.FolderBrowserDialog();
- dlg.Description = "请选择需要测试的图片文件夹";
- if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
- {
- string selectedFolder = dlg.SelectedPath;
- var files = Directory.GetFiles(selectedFolder);
- foreach (var file in files)
- {
- string extension = System.IO.Path.GetExtension(file);
- if (extension == ".jpg" || extension == ".bmp" || extension == ".png" || extension == ".txt")
- {
- _imagesReadyForTest1.Enqueue(file);
- }
- }
- _imageCount = _imagesReadyForTest1.Count;
- if (_imageCount > 0)
- {
- DoImageReading1();
- }
- else
- {
- MessageBox.Show("未加载到有效的图像数据");
- }
- }
- }
- /// <summary>
- /// 用户点击了解冻按钮
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void OnUnfreezeClick(object sender, RoutedEventArgs e)
- {
- _detect1.ManuallyUnfreeze();
- }
- /// <summary>
- /// 用户点击了停止播放按钮
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void OnStopReading1Click(object sender, RoutedEventArgs e)
- {
- if (_videoReadyForTest1.Count > 0)
- {
- _videoReadyForTest1.Clear();
- }
- StopVideoReading1();
- }
- /// <summary>
- /// 用户点击了加载视频按钮
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void OnLoadVideo2Click(object sender, RoutedEventArgs e)
- {
- if (_videoReadyForTest2.Count > 0)
- {
- _videoReadyForTest2.Clear();
- }
- StopVideoReading2();
- Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();
- openFileDialog.Filter = "视频文件|*.mp4;*.avi";
- openFileDialog.Multiselect = true;
- openFileDialog.Title = "选择一个或多个视频";
- if (openFileDialog.ShowDialog() ?? false)
- {
- foreach (string filename in openFileDialog.FileNames)
- {
- _videoReadyForTest2.Enqueue(filename);
- }
- DoVideoReading2();
- }
- }
- /// <summary>
- /// 用户点击了停止播放按钮
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void OnStopReading2Click(object sender, RoutedEventArgs e)
- {
- if (_videoReadyForTest2.Count > 0)
- {
- _videoReadyForTest2.Clear();
- }
- StopVideoReading2();
- }
- /// <summary>
- /// 用户点击了关闭按钮
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void OnWindowClosing(object sender, System.ComponentModel.CancelEventArgs e)
- {
- if (_videoReadyForTest1.Count > 0)
- {
- _videoReadyForTest1.Clear();
- }
- StopVideoReading1();
- if (_videoReadyForTest2.Count > 0)
- {
- _videoReadyForTest2.Clear();
- }
- StopVideoReading2();
- }
- #endregion
- #region 其他私有函数
- private void StopVideoReading1()
- {
- _readEvent1.Set();
- lock (_locker1)
- {
- if (_reader1 != null)
- {
- _reader1.Close();
- _reader1 = null;
- }
- }
- }
- private void DoVideoReading1()
- {
- Task.Run(() =>
- {
- try
- {
- if (_videoReadyForTest1.Count <= 0)
- {
- return;
- }
- string videoFilePath = _videoReadyForTest1.Dequeue();
- _readEvent1.Set();
- int frameCount = 0;
- int sleepTime = 0;
- lock (_locker1)
- {
- _reader1 = new VideoFileReader();
- _reader1.Open(videoFilePath);
- var frameRate = _reader1.FrameRate;
- frameCount = (int)_reader1.FrameCount;
- sleepTime = (int)(1000 / frameRate.ToDouble());
- }
- _readEvent1.Reset();
- for (int ni = 0; ni < frameCount; ni++)
- {
- if (_readEvent1.WaitOne(1))
- {
- break;
- }
- Bitmap img = null;
- lock (_locker1)
- {
- img = _reader1.ReadVideoFrame(ni);
- }
- if (img != null)
- {
- // 测试图像
- var detectStartTime = Environment.TickCount;
- CurrentVideoState nAuto = CurrentVideoState.Notjudged;
- var rawImage = BitmapToRawImage(img);
- if (_useIntptrImage)
- {
- GCHandle hObject = GCHandle.Alloc(rawImage.DataBuffer, GCHandleType.Pinned);
- IntPtr pPbject = hObject.AddrOfPinnedObject();
- IntptrRawImage intptrImage = new IntptrRawImage(pPbject, rawImage.Width, rawImage.Height, rawImage.ColorType);
- nAuto = _detect1.ImgDataCalculateCS(intptrImage);
- if (hObject.IsAllocated)
- {
- hObject.Free();
- }
- }
- else
- {
- nAuto = _detect1.ImgDataCalculateCS(rawImage);
- }
- rawImage.Dispose();
- var detectTimeUsed = Environment.TickCount - detectStartTime;
- // 显示图像
- Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(() =>
- {
- TestImage1.Source = BitmapToBitmapImage(img);
- VideoProgressBar1.Value = Convert.ToDouble(ni) / frameCount * 100;
- if (nAuto == CurrentVideoState.Stationary )
- {
- StatusText1.Text = "静置";
- }
- else if (nAuto == CurrentVideoState.Moving)
- {
- StatusText1.Text = "运行";
- }
- else if (nAuto == CurrentVideoState.Error)
- {
- StatusText1.Text = "error";
- }
- else
- {
- StatusText1.Text = "不能判断";
- }
- }));
- // sleep
- var finalSleepTime = sleepTime - detectTimeUsed;
- if (finalSleepTime < 0)
- {
- finalSleepTime = 0;
- }
- if (_readEvent1.WaitOne(finalSleepTime))
- {
- break;
- }
- }
- }
- DoVideoReading1();
- }
- catch (Exception excep)
- {
- System.Windows.MessageBox.Show("读取视频出错!:" + excep.Message);
- }
- });
- }
- private void DoImageReading1()
- {
- Task.Run(() =>
- {
- try
- {
- if (_imagesReadyForTest1.Count <= 0)
- {
- return;
- }
- double frameRate = 20;
- int sleepTime = (int)(1000 / frameRate);
- string imageFilePath = _imagesReadyForTest1.Dequeue();
- int ni = _imageCount - _imagesReadyForTest1.Count;
- _readEvent1.Reset();
- string extension = System.IO.Path.GetExtension(imageFilePath);
- Bitmap img = null;
- if (extension == ".txt")
- {
- var rawImage = RawImage.ReadRawImageFromFile(imageFilePath);
- img = RawImageToBitmap(rawImage);
- }
- else
- {
- img = new Bitmap(imageFilePath);
- }
- if(img!=null)
- {
- // 测试图像
- var detectStartTime = Environment.TickCount;
- CurrentVideoState nAuto = CurrentVideoState.Notjudged;
- var rawImage = BitmapToRawImage(img);
- if (_useIntptrImage)
- {
- GCHandle hObject = GCHandle.Alloc(rawImage.DataBuffer, GCHandleType.Pinned);
- IntPtr pPbject = hObject.AddrOfPinnedObject();
- IntptrRawImage intptrImage = new IntptrRawImage(pPbject, rawImage.Width, rawImage.Height, rawImage.ColorType);
- nAuto = _detect1.ImgDataCalculateCS(intptrImage);
- if (hObject.IsAllocated)
- {
- hObject.Free();
- }
- }
- else
- {
- nAuto = _detect1.ImgDataCalculateCS(rawImage);
- }
- rawImage.Dispose();
- var detectTimeUsed = Environment.TickCount - detectStartTime;
- // 显示图像
- Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(() =>
- {
- TestImage1.Source = BitmapToBitmapImage(img);
- VideoProgressBar1.Value = Convert.ToDouble(ni) / _imageCount * 100;
- if (nAuto == CurrentVideoState.Stationary)
- {
- StatusText1.Text = "静置";
- }
- else if (nAuto == CurrentVideoState.Moving)
- {
- StatusText1.Text = "运行";
- }
- else if (nAuto == CurrentVideoState.Error)
- {
- StatusText1.Text = "error";
- }
- else
- {
- StatusText1.Text = "不能判断";
- }
- }));
- // sleep
- var finalSleepTime = sleepTime - detectTimeUsed;
- if (finalSleepTime < 0)
- {
- finalSleepTime = 1;
- }
- _readEvent1.WaitOne(finalSleepTime);
- }
- DoImageReading1();
- }
- catch (Exception excep)
- {
- System.Windows.MessageBox.Show("读取图像出错!:" + excep.Message);
- }
- });
- }
- private void StopVideoReading2()
- {
- _readEvent2.Set();
- lock (_locker2)
- {
- if (_reader2 != null)
- {
- _reader2.Close();
- _reader2 = null;
- }
- }
- }
- private void DoVideoReading2()
- {
- Task.Run(() =>
- {
- try
- {
- if (_videoReadyForTest2.Count <= 0)
- {
- return;
- }
- string videoFilePath = _videoReadyForTest2.Dequeue();
- _readEvent2.Set();
- int frameCount = 0;
- int sleepTime = 0;
- lock (_locker2)
- {
- _reader2 = new VideoFileReader();
- _reader2.Open(videoFilePath);
- var frameRate = _reader2.FrameRate;
- frameCount = (int)_reader2.FrameCount;
- sleepTime = (int)(1000 / frameRate.ToDouble());
- }
- _readEvent2.Reset();
- for (int ni = 0; ni < frameCount; ni++)
- {
- if (_readEvent2.WaitOne(1))
- {
- break;
- }
- Bitmap img = null;
- lock (_locker2)
- {
- img = _reader2.ReadVideoFrame(ni);
- }
- if (img != null)
- {
- // 测试图像
- var detectStartTime = Environment.TickCount;
- CurrentVideoState nAuto = CurrentVideoState.Notjudged;
- var rawImage = BitmapToRawImage(img);
- if (_useIntptrImage)
- {
- GCHandle hObject = GCHandle.Alloc(rawImage.DataBuffer, GCHandleType.Pinned);
- IntPtr pPbject = hObject.AddrOfPinnedObject();
- IntptrRawImage intptrImage = new IntptrRawImage(pPbject, rawImage.Width, rawImage.Height, rawImage.ColorType);
- nAuto = _detect2.ImgDataCalculateCS(intptrImage);
- if (hObject.IsAllocated)
- {
- hObject.Free();
- }
- }
- else
- {
- nAuto = _detect2.ImgDataCalculateCS(rawImage);
- }
- rawImage.Dispose();
- var detectTimeUsed = Environment.TickCount - detectStartTime;
- // 显示图像
- Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(() =>
- {
- TestImage2.Source = BitmapToBitmapImage(img);
- VideoProgressBar2.Value = Convert.ToDouble(ni) / frameCount * 100;
- if (nAuto == CurrentVideoState.Stationary)
- {
- StatusText2.Text = "静置";
- }
- else if (nAuto == CurrentVideoState.Moving)
- {
- StatusText2.Text = "运行";
- }
- else if (nAuto == CurrentVideoState.Error)
- {
- StatusText2.Text = "error";
- }
- else
- {
- StatusText2.Text = "不能判断";
- }
- }));
- // sleep
- var finalSleepTime = sleepTime - detectTimeUsed;
- if (finalSleepTime < 0)
- {
- finalSleepTime = 0;
- }
- if (_readEvent2.WaitOne(finalSleepTime))
- {
- break;
- }
- }
- }
- DoVideoReading2();
- }
- catch (Exception excep)
- {
- System.Windows.MessageBox.Show("读取视频出错!:" + excep.Message);
- }
- });
- }
- /// <summary>
- /// 将Bitmap转换为BitmapImage
- /// </summary>
- /// <param name="img"></param>
- /// <returns></returns>
- private BitmapImage BitmapToBitmapImage(Bitmap img)
- {
- BitmapImage bmpimg = new BitmapImage();
- using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
- {
- img.Save(ms, ImageFormat.Png);
- bmpimg.BeginInit();
- bmpimg.StreamSource = ms;
- bmpimg.CacheOption = BitmapCacheOption.OnLoad;
- bmpimg.EndInit();
- bmpimg.Freeze();
- ms.Dispose();
- }
- return bmpimg;
- }
- /// <summary>
- /// 将System.Drawimg.Bitmap转为RawImage
- /// </summary>
- /// <param name="image"></param>
- /// <param name="keepChannel"></param>
- /// <returns></returns>
- public static RawImage BitmapToRawImage(Bitmap image, bool keepColorType = false)
- {
- int width = image.Width;
- int height = image.Height;
- PixelFormat pixelFormat = image.PixelFormat;
- if (pixelFormat != PixelFormat.Format24bppRgb && pixelFormat != PixelFormat.Format32bppArgb
- && pixelFormat != PixelFormat.Format8bppIndexed && pixelFormat != PixelFormat.Format16bppGrayScale)
- {
- throw new Exception("Unexpected image pixel format:" + pixelFormat);
- }
- EnumColorType origColorType = EnumColorType.Gray8;
- int origBytesPerPixel = 1;
- if (pixelFormat == PixelFormat.Format8bppIndexed)
- {
- origColorType = EnumColorType.Gray8;
- origBytesPerPixel = 1;
- }
- else if (pixelFormat == PixelFormat.Format16bppGrayScale)
- {
- origColorType = EnumColorType.Gray16;
- origBytesPerPixel = 2;
- }
- else if (pixelFormat == PixelFormat.Format24bppRgb)
- {
- // 注意Bitmap里的24bppRgb其实通道顺序是BGR
- origColorType = EnumColorType.Bgr;
- origBytesPerPixel = 3;
- }
- else
- {
- // 注意Bitmap里的32Argb其实通道顺序是Bgra
- origColorType = EnumColorType.Bgra;
- origBytesPerPixel = 4;
- }
- EnumColorType dstColorType;
- int dstBytesPerPixel;
- if (keepColorType)
- {
- dstColorType = origColorType;
- dstBytesPerPixel = origBytesPerPixel;
- }
- else
- {
- // 如果没有指定要keepColorType的话,默认都转成BGR
- dstColorType = EnumColorType.Bgr;
- dstBytesPerPixel = 3;
- }
- var bmData = image.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, pixelFormat);
- byte[] dstDataArray = new byte[width * height * dstBytesPerPixel];
- unsafe
- {
- int stride = bmData.Stride;
- int dstStride = width * dstBytesPerPixel;
- IntPtr ptr = bmData.Scan0;
- IntPtr ptrH, ptrW;
- // 原图和目标图的ColorType相同
- if (origColorType == dstColorType)
- {
- for (int nh = 0; nh < height; nh++)
- {
- ptrH = IntPtr.Add(ptr, nh * stride);
- Marshal.Copy(ptrH, dstDataArray, nh * dstStride, dstStride);
- }
- }
- // 原图和目标图的ColorType不同
- else
- {
- // 如果原图是8位灰度图
- if (origColorType == EnumColorType.Gray8)
- {
- if (dstColorType == EnumColorType.Gray16)
- {
- byte gray;
- int dstOffset;
- for (int nh = 0; nh < height; nh++)
- {
- ptrH = IntPtr.Add(ptr, nh * stride);
- for (int nw = 0; nw < width; nw++)
- {
- ptrW = IntPtr.Add(ptrH, nw * origBytesPerPixel);
- gray = Marshal.ReadByte(ptrW);
- dstOffset = nh * dstStride + nw * dstBytesPerPixel;
- dstDataArray[dstOffset] = gray;
- // 高位为0,因此不用赋值
- }
- }
- }
- else
- {
- byte gray;
- int dstOffset;
- for (int nh = 0; nh < height; nh++)
- {
- ptrH = IntPtr.Add(ptr, nh * stride);
- for (int nw = 0; nw < width; nw++)
- {
- ptrW = IntPtr.Add(ptrH, nw * origBytesPerPixel);
- gray = Marshal.ReadByte(ptrW);
- dstOffset = nh * dstStride + nw * dstBytesPerPixel;
- dstDataArray[dstOffset] = gray;
- dstDataArray[dstOffset + 1] = gray;
- dstDataArray[dstOffset + 2] = gray;
- }
- }
- if (dstColorType == EnumColorType.Bgra)
- {
- for (int nh = 0; nh < height; nh++)
- {
- for (int nw = 0; nw < width; nw++)
- {
- dstOffset = nh * dstStride + nw * dstBytesPerPixel;
- dstDataArray[dstOffset + 3] = 255;
- }
- }
- }
- }
- }
- // 如果原图是BGR彩色图
- if (origColorType == EnumColorType.Bgr)
- {
- if (dstColorType == EnumColorType.Gray8 || dstColorType == EnumColorType.Gray16)
- {
- byte red, green, blue, gray;
- int dstOffset;
- for (int nh = 0; nh < height; nh++)
- {
- ptrH = IntPtr.Add(ptr, nh * stride);
- for (int nw = 0; nw < width; nw++)
- {
- ptrW = IntPtr.Add(ptrH, nw * origBytesPerPixel);
- blue = Marshal.ReadByte(ptrW);
- ptrW = IntPtr.Add(ptrW, 1);
- green = Marshal.ReadByte(ptrW);
- ptrW = IntPtr.Add(ptrW, 1);
- red = Marshal.ReadByte(ptrW);
- gray = RawImage.PixelRGBToGray(red, green, blue);
- dstOffset = nh * dstStride + nw * dstBytesPerPixel;
- dstDataArray[dstOffset] = gray;
- }
- }
- }
- if (dstColorType == EnumColorType.Bgra)
- {
- int dstOffset;
- for (int nh = 0; nh < height; nh++)
- {
- ptrH = IntPtr.Add(ptr, nh * stride);
- for (int nw = 0; nw < width; nw++)
- {
- ptrW = IntPtr.Add(ptrH, nw * origBytesPerPixel);
- dstOffset = nh * dstStride + nw * dstBytesPerPixel;
- Marshal.Copy(ptrW, dstDataArray, dstOffset, 3);
- dstDataArray[dstOffset + 3] = 255;
- }
- }
- }
- }
- // 如果原图是BGRA彩色图
- if (origColorType == EnumColorType.Bgra)
- {
- if (dstColorType == EnumColorType.Gray8 || dstColorType == EnumColorType.Gray16)
- {
- byte red, green, blue, gray;
- int dstOffset;
- for (int nh = 0; nh < height; nh++)
- {
- ptrH = IntPtr.Add(ptr, nh * stride);
- for (int nw = 0; nw < width; nw++)
- {
- ptrW = IntPtr.Add(ptrH, nw * origBytesPerPixel);
- blue = Marshal.ReadByte(ptrW);
- ptrW = IntPtr.Add(ptrW, 1);
- green = Marshal.ReadByte(ptrW);
- ptrW = IntPtr.Add(ptrW, 1);
- red = Marshal.ReadByte(ptrW);
- gray = RawImage.PixelRGBToGray(red, green, blue);
- dstOffset = nh * dstStride + nw * dstBytesPerPixel;
- dstDataArray[dstOffset] = gray;
- }
- }
- }
- if (dstColorType == EnumColorType.Bgr)
- {
- int dstOffset;
- for (int nh = 0; nh < height; nh++)
- {
- ptrH = IntPtr.Add(ptr, nh * stride);
- for (int nw = 0; nw < width; nw++)
- {
- ptrW = IntPtr.Add(ptrH, nw * origBytesPerPixel);
- dstOffset = nh * dstStride + nw * dstBytesPerPixel;
- Marshal.Copy(ptrW, dstDataArray, dstOffset, 3);
- }
- }
- }
- }
- }
- }
- image.UnlockBits(bmData);
- return new RawImage(dstDataArray, width, height, dstColorType);
- }
- /// <summary>
- /// 将RawImage转为System.Drawing.Bitmap
- /// </summary>
- /// <param name="image"></param>
- /// <returns></returns>
- public static Bitmap RawImageToBitmap(RawImage image)
- {
- int width = image.Width;
- int height = image.Height;
- EnumColorType colorType = image.ColorType;
- PixelFormat pixelFormat;
- EnumColorType dstColorType;
- RawImage clonedImage;
- switch (colorType)
- {
- case EnumColorType.Gray8:
- clonedImage = image;
- pixelFormat = PixelFormat.Format8bppIndexed;
- dstColorType = EnumColorType.Gray8;
- break;
- case EnumColorType.Gray16:
- clonedImage = image;
- pixelFormat = PixelFormat.Format16bppGrayScale;
- dstColorType = EnumColorType.Gray16;
- break;
- case EnumColorType.GrayF32:
- clonedImage = image.Clone(EnumColorType.Gray8);
- pixelFormat = PixelFormat.Format8bppIndexed;
- dstColorType = EnumColorType.Gray8;
- break;
- case EnumColorType.Bgr:
- clonedImage = image;
- pixelFormat = PixelFormat.Format24bppRgb;
- dstColorType = EnumColorType.Bgr;
- break;
- case EnumColorType.Rgb:
- clonedImage = image.Clone(EnumColorType.Bgr);
- pixelFormat = PixelFormat.Format24bppRgb;
- dstColorType = EnumColorType.Bgr;
- break;
- case EnumColorType.Bgra:
- clonedImage = image;
- pixelFormat = PixelFormat.Format32bppArgb;
- dstColorType = EnumColorType.Bgra;
- break;
- case EnumColorType.Rgba:
- clonedImage = image.Clone(EnumColorType.Bgra);
- pixelFormat = PixelFormat.Format32bppArgb;
- dstColorType = EnumColorType.Bgra;
- break;
- default:
- throw new ArgumentOutOfRangeException("Unexpected image.colorType.");
- }
- Bitmap dstBmp = new Bitmap(width, height, pixelFormat);
- var bmData = dstBmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, pixelFormat);
- unsafe
- {
- int stride = bmData.Stride;
- IntPtr ptr = bmData.Scan0;
- byte[] dataBuffer = clonedImage.DataBuffer;
- int bytePerPixel = clonedImage.BytesPerPixel;
- if (stride == width * bytePerPixel)
- {
- Marshal.Copy(dataBuffer, 0, ptr, width * height * bytePerPixel);
- }
- else
- {
- IntPtr ptrDst;
- for (int ni = 0; ni < height; ni++)
- {
- ptrDst = IntPtr.Add(ptr, ni * stride);
- Marshal.Copy(dataBuffer, ni * width * bytePerPixel, ptrDst, width * bytePerPixel);
- }
- }
- }
- dstBmp.UnlockBits(bmData);
- // 灰度图像需要写调色板
- if (dstColorType == EnumColorType.Gray8)
- {
- var palette = dstBmp.Palette;
- for (int ni = 0; ni < 256; ni++)
- {
- palette.Entries[ni] = Color.FromArgb(ni, ni, ni);
- }
- dstBmp.Palette = palette;
- }
- return dstBmp;
- }
- #endregion
- }
- }
|