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 @   WellMandala  阅读(2553)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端
点击右上角即可分享
微信分享提示