C#將圖片轉換層RGB32的byte

網上發現C#將圖片轉換層RGB32的byte的結果很少,找了很多代碼,經過自己的多次調試,終於實現了。具體代碼片段如下:


   /// <summary>
        /// Bitmap轉換層RGB32
        /// </summary>
        /// <param name="Source">Bitmap圖片</param>
        /// <returns></returns>
        public static byte[] GetRgb32_From_Bitmap(Bitmap Source)
        {
            bool bError = false;
            string errorMsg = string.Empty;

            return GetRgb32_From_Bitmap(Source, ref bError, ref errorMsg);
        }


        /// <summary>
        /// Bitmap轉換層RGB32
        /// </summary>
        /// <param name="Source">Bitmap圖片</param>
        /// <returns></returns>
        public static byte[] GetRgb32_From_Bitmap(Bitmap Source, ref bool bError, ref string errorMsg)
        {
            bError = false;

            int lPicWidth = Source.Width;
            int lPicHeight = Source.Height;

            Rectangle rect = new Rectangle(0, 0, lPicWidth, lPicHeight);
            System.Drawing.Imaging.BitmapData bmpData = Source.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, Source.PixelFormat);
            IntPtr iPtr = bmpData.Scan0;

            int picSize = lPicWidth * lPicHeight * 4;

            byte[] pRrgaByte = new byte[picSize];

            System.Runtime.InteropServices.Marshal.Copy(iPtr, pRrgaByte, 0, picSize);

            Source.UnlockBits(bmpData);

            int iPoint = 0;
            int A = 0;

            try
            {
                //for (int iRow = 0; iRow < lPicHeight; iRow++)
                //{
                //    for (int jCol = 0; jCol < lPicWidth; jCol++)
                //    {
                //        pRrgaByte[4 * (iRow * lPicWidth + jCol) + 0] = Convert.ToByte(pRrgaByte[iPoint++]);
                //        pRrgaByte[4 * (iRow * lPicWidth + jCol) + 1] = Convert.ToByte(pRrgaByte[iPoint++]);
                //        pRrgaByte[4 * (iRow * lPicWidth + jCol) + 2] = Convert.ToByte(pRrgaByte[iPoint++]);
                //        pRrgaByte[4 * (iRow * lPicWidth + jCol) + 3] = Convert.ToByte(A);
                //    }
                //}

                bError = true;
                errorMsg = "BMP數據轉換成功";

                return pRrgaByte;
            }
            catch (Exception exp)
            {
                pRrgaByte = null;

                bError = false;
                errorMsg = exp.ToString();
                //throw;
            }

            return null;
        }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章