C#使用內存和指針方式將字節數組轉換為Bitmap


        /// <summary>
        /// 指針方式轉
        /// </summary>
        /// <param name="Width">圖像的寬</param>
        /// <param name="Height">圖像的高</param>
        /// <param name="pointer">指針</param>
        private void Mono8ToBitmap(int Width,int Height,IntPtr pointer)
        {
            Bitmap bmp = new Bitmap(Width, Height, Width * 1, PixelFormat.Format8bppIndexed, pointer);
            ColorPalette cp = bmp.Palette;
            // init palette
            for (int i = 0; i < 256; i++)
            {
                cp.Entries[i] = Color.FromArgb(i, i, i);
            }
            // set palette back
            bmp.Palette = cp;
            pictureBox1.Invalidate();
        }

        private void BytesToBitmap(int Width,int Height)
        {
            //一,內存復制方式:
            Bitmap myimg = new Bitmap(Width, Height, PixelFormat.Format8bppIndexed);
            BitmapData mydata;
            mydata = myimg.LockBits(new Rectangle(0, 0, myimg.Width, myimg.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
            System.Runtime.InteropServices.Marshal.Copy(b, 0, mydata.Scan0, b.Length);
            myimg.UnlockBits(mydata);
            pictureBox1.Invalidate();
        }

 內存方式2:如果碰上電腦性能差,圖像又很大的情況

                           if (image==null)
                            {
                                image = new Bitmap(e.Width, e.Height, PixelFormat.Format8bppIndexed);
                            }
                            bmpData = image.LockBits(new Rectangle(0, 0, e.Width, e.Height), ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
                            //用Marshal的Copy方法,將剛才得到的內存字節數組復制到BitmapData中
                            System.Runtime.InteropServices.Marshal.Copy(e.Buffer, 0, bmpData.Scan0, bmpData.Stride * e.Height);
                            image.UnlockBits(bmpData);  // 解鎖內存區域  
                            ColorPalette tempPalette;
                            using (Bitmap tempBmp = new Bitmap(1, 1, PixelFormat.Format8bppIndexed))
                            {
                                tempPalette = tempBmp.Palette;
                            }
                            for (int i = 0; i < 256; i++)
                            {
                                tempPalette.Entries[i] = Color.FromArgb(i, i, i);
                            }
                            image.Palette = tempPalette;
                            picturebox.BeginInvoke(new Action(() =>
                            {
                                picturebox.Image=image;
                            }));

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM