Tools.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Drawing;
  4. using System.Drawing.Imaging;
  5. using System.Runtime.InteropServices;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. namespace TUCamera
  10. {
  11. /// <summary>
  12. /// Bitmap转化
  13. /// </summary>
  14. public static class Tools
  15. {
  16. public static Bitmap ToBitmap(this byte[] rawValues, int width, int height, PixelFormat pixelFormat)
  17. {
  18. //// 申请目标位图的变量,并将其内存区域锁定
  19. try
  20. {
  21. var currBitmap = new Bitmap(width, height, pixelFormat);
  22. var rect = new Rectangle(0, 0, width, height);
  23. var bitmapData = currBitmap.LockBits(rect, ImageLockMode.WriteOnly, pixelFormat);
  24. IntPtr iptr = bitmapData.Scan0; // 获取bmpData的内存起始位置
  25. int size = width * height;
  26. if (pixelFormat == PixelFormat.Format24bppRgb)
  27. size *= 3;
  28. Marshal.Copy(rawValues, 0, iptr, size);
  29. currBitmap.UnlockBits(bitmapData);
  30. return currBitmap;
  31. }
  32. catch
  33. {
  34. return null;
  35. }
  36. }
  37. public static byte[] ToByteArray(this Bitmap bitmap)
  38. {
  39. BitmapData bmpdata = null;
  40. try
  41. {
  42. bmpdata = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, bitmap.PixelFormat);
  43. int numbytes = bmpdata.Stride * bitmap.Height;
  44. byte[] bytedata = new byte[numbytes];
  45. IntPtr ptr = bmpdata.Scan0;
  46. Marshal.Copy(ptr, bytedata, 0, numbytes);
  47. return bytedata;
  48. }
  49. finally
  50. {
  51. if (bmpdata != null)
  52. bitmap.UnlockBits(bmpdata);
  53. }
  54. }
  55. public static Bitmap ToBitmap(this TUCAMAPI.TUCAM_FRAME frame)
  56. {
  57. var width = (int)(frame.usWidth);
  58. var height = (int)(frame.usHeight);
  59. int nSize = (int)(frame.uiImgSize + frame.usHeader);
  60. var buff = new byte[nSize];
  61. Marshal.Copy(frame.pBuffer, buff, 0, nSize);
  62. Buffer.BlockCopy(buff, (int)(frame.usHeader), buff, 0, (int)(frame.uiImgSize));
  63. Bitmap bitmap;
  64. if (frame.ucChannels == 1)
  65. {
  66. bitmap = buff.ToBitmap(width, height, PixelFormat.Format8bppIndexed); ;
  67. }
  68. else
  69. {
  70. bitmap = buff.ToBitmap(width, height, PixelFormat.Format24bppRgb); ;
  71. }
  72. return bitmap;
  73. }
  74. }
  75. }