using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace MeterVision.FreeAi
{
    public class FaImageHelper
    {
        //根据JPG的文件名获取RGB565的图像数据
        public static short[] getRGB565Array_from_jpgfile(string jpgFilePath,FaLog faLog)
        {
            if(jpgFilePath == null)
            {
                faLog.Appendln_mcuLog("jpgFilePath null error.");
                return null;             
            }

            //判断文件是存在
            if (!File.Exists(jpgFilePath))
            {
                faLog.Appendln_mcuLog(jpgFilePath + "not exits");
                return null;
            }

            using (Bitmap bmp = new Bitmap(jpgFilePath))
            {
                int width = bmp.Width;
                int height = bmp.Height;
                string message = string.Format("width = %d,height = %d\n", width, height);
                faLog.Appendln_mcuLog(message);

                //创建数组存储RGB565数据
                short[] rgb565Data = new short[width * height];

                //锁定位图内存
                BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
                IntPtr ptr = bmpData.Scan0;

                //创建数据存储RGB888数据
                byte[] rgb888Data = new byte[Math.Abs(bmpData.Stride) * height];

                //将像素数据拷贝到字节数组中
                Marshal.Copy(ptr, rgb888Data, 0, rgb888Data.Length);

                // 逐个像素转换为 RGB565 格式，并进行上下颠倒处理
                for (int y = 0; y < height; y++)
                {
                    for (int x = 0; x < width; x++)
                    {
                        // 颠倒行的顺序
                        int invertedY = height - 1 - y;

                        //int index = y * bmpData.Stride + x * 3;
                        int index = invertedY * bmpData.Stride + x * 3;

                        byte r = rgb888Data[index + 2]; // R 通道
                        byte g = rgb888Data[index + 1]; // G 通道
                        byte b = rgb888Data[index];     // B 通道

                        // 将 RGB888 转换为 RGB565
                        short rgb565 = (short)(((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3));
                        rgb565Data[y * width + x] = rgb565;
                    }
                }

                //解锁位图

                bmp.UnlockBits(bmpData);
                bmp.Dispose();

                return rgb565Data;
            }//using Bitmap
        }


        /////////////////////////////////////////////////////////////////////
    }
}
