c#内存法数组转化图像显示

 1             int h = 500;
 2             int w = 500;
 3             byte[] huidushuzu=new byte[500*500*3];  
 4             for(int k=0;k<(500*500*3);k+=3)
 5             {
 6                 double kk = (double)k;
 7                 huidushuzu[k + 2] = huidushuzu[k + 1]=huidushuzu[k]= (byte)(((kk + 1.0) / (500.0 * 500.0*3.0)) * 255.0);
 8             }
 9             //创建bitmap对象,用于处理图像
10             Bitmap mybmp = new Bitmap(w, h, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
11             //从创建的mybmp中锁定rect范围的像素,生成bitmapdata
12             Rectangle rect = new Rectangle(0, 0, 500, 500);
13             System.Drawing.Imaging.BitmapData bitmapData = mybmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, mybmp.PixelFormat);
14             //得到首地址
15             IntPtr ptr = bitmapData.Scan0;
16             int bytes = mybmp.Width * mybmp.Height * 3;//定义被锁定的数组大小
17             System.Runtime.InteropServices.Marshal.Copy(huidushuzu, 0, ptr, bytes);//把数组huidushuzu复制到位图内,0-起始位置,bytes-长度
18             mybmp.UnlockBits(bitmapData);//解锁像素
19             //用picturebox显示图像
20             Image img = Image.FromHbitmap(mybmp.GetHbitmap());
21             pictureBox1.Image = img;
22             pictureBox1.Show();

bitmap.SetPixel方法可以更改像素值,但是需要使用循环,速度较慢。使用内存法,用marshal.copy将图像数据复制到内存进行操作,提升了程序运行速度。

原文地址:https://www.cnblogs.com/winterbear/p/13629952.html