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;
                            }));

 

posted @ 2021-11-01 21:48  WellMandala  阅读(2415)  评论(0编辑  收藏  举报