FaImageHelper.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Drawing;
  4. using System.Drawing.Imaging;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Runtime.InteropServices;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. namespace MeterVision.FreeAi
  11. {
  12. public class FaImageHelper
  13. {
  14. //根据JPG的文件名获取RGB565的图像数据
  15. public static short[] getRGB565Array_from_jpgfile(string jpgFilePath,FaLog faLog)
  16. {
  17. if(jpgFilePath == null)
  18. {
  19. faLog.Appendln_mcuLog("jpgFilePath null error.");
  20. return null;
  21. }
  22. //判断文件是存在
  23. if (!File.Exists(jpgFilePath))
  24. {
  25. faLog.Appendln_mcuLog(jpgFilePath + "not exits");
  26. return null;
  27. }
  28. using (Bitmap bmp = new Bitmap(jpgFilePath))
  29. {
  30. int width = bmp.Width;
  31. int height = bmp.Height;
  32. string message = string.Format("width = %d,height = %d\n", width, height);
  33. faLog.Appendln_mcuLog(message);
  34. //创建数组存储RGB565数据
  35. short[] rgb565Data = new short[width * height];
  36. //锁定位图内存
  37. BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
  38. IntPtr ptr = bmpData.Scan0;
  39. //创建数据存储RGB888数据
  40. byte[] rgb888Data = new byte[Math.Abs(bmpData.Stride) * height];
  41. //将像素数据拷贝到字节数组中
  42. Marshal.Copy(ptr, rgb888Data, 0, rgb888Data.Length);
  43. // 逐个像素转换为 RGB565 格式,并进行上下颠倒处理
  44. for (int y = 0; y < height; y++)
  45. {
  46. for (int x = 0; x < width; x++)
  47. {
  48. // 颠倒行的顺序
  49. int invertedY = height - 1 - y;
  50. //int index = y * bmpData.Stride + x * 3;
  51. int index = invertedY * bmpData.Stride + x * 3;
  52. byte r = rgb888Data[index + 2]; // R 通道
  53. byte g = rgb888Data[index + 1]; // G 通道
  54. byte b = rgb888Data[index]; // B 通道
  55. // 将 RGB888 转换为 RGB565
  56. short rgb565 = (short)(((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3));
  57. rgb565Data[y * width + x] = rgb565;
  58. }
  59. }
  60. //解锁位图
  61. bmp.UnlockBits(bmpData);
  62. bmp.Dispose();
  63. return rgb565Data;
  64. }//using Bitmap
  65. }
  66. /////////////////////////////////////////////////////////////////////
  67. }
  68. }