c# – 生成16位灰度BitmapData并保存到文件
发布时间:2020-12-15 19:39:34 所属栏目:百科 来源:网络整理
导读:我试图从随机数据中生成C#中的16位灰度位图.但是它在Marshal.Copy上崩溃了. 这是我的代码: Bitmap b16bpp; private void GenerateDummy16bitImage() { b16bpp = new Bitmap(IMAGE_WIDTH,IMAGE_HEIGHT,System.Drawing.Imaging.PixelFormat.Format16bppGraySc
我试图从随机数据中生成C#中的16位灰度位图.但是它在Marshal.Copy上崩溃了.
这是我的代码: Bitmap b16bpp; private void GenerateDummy16bitImage() { b16bpp = new Bitmap(IMAGE_WIDTH,IMAGE_HEIGHT,System.Drawing.Imaging.PixelFormat.Format16bppGrayScale); var rect = new Rectangle(0,IMAGE_WIDTH,IMAGE_HEIGHT); var bitmapData = b16bpp.LockBits(rect,ImageLockMode.WriteOnly,b16bpp.PixelFormat); // Calculate the number of bytes required and allocate them. var numberOfBytes = bitmapData.Stride * IMAGE_HEIGHT * 2; var bitmapBytes = new short[numberOfBytes]; // Fill the bitmap bytes with random data. var random = new Random(); for (int x = 0; x < IMAGE_WIDTH; x++) { for (int y = 0; y < IMAGE_HEIGHT; y++) { var i = ((y * IMAGE_WIDTH) + x) * 2; // 16bpp // Generate the next random pixel color value. var value = (short)random.Next(5); bitmapBytes[i] = value; // BLUE bitmapBytes[i + 1] = value; // GREEN bitmapBytes[i + 2] = value; // RED // bitmapBytes[i + 3] = 0xFF; // ALPHA } } // Copy the randomized bits to the bitmap pointer. var ptr = bitmapData.Scan0; Marshal.Copy(bitmapBytes,ptr,numberOfBytes);//crashes here // Unlock the bitmap,we're all done. b16bpp.UnlockBits(bitmapData); b16bpp.Save("random.bmp",ImageFormat.Bmp); Debug.WriteLine("saved"); } 例外是: mscorlib.dll中发生了未处理的“System.AccessViolationException”类型异常 这不是我的代码.我发现它与32位Bitmaps和修改有关.但我想我错过了一些东西,因为我对C#很新. 基本上,我只需要在BitmapData中包含一个short数组. 解决方法
我纠正了你的一些错误(大多是错误的大小).但它仍会在b16bpp.Save()上崩溃,因为
GDI+ does not support saving 16bit grayscale images.
Bitmap b16bpp; private void GenerateDummy16bitImage() { b16bpp = new Bitmap(IMAGE_WIDTH,System.Drawing.Imaging.PixelFormat.Format16bppGrayScale); var rect = new Rectangle(0,IMAGE_HEIGHT); var bitmapData = b16bpp.LockBits(rect,b16bpp.PixelFormat); // Calculate the number of bytes required and allocate them. var numberOfBytes = bitmapData.Stride * IMAGE_HEIGHT; var bitmapBytes = new short[IMAGE_WIDTH * IMAGE_HEIGHT]; // Fill the bitmap bytes with random data. var random = new Random(); for (int x = 0; x < IMAGE_WIDTH; x++) { for (int y = 0; y < IMAGE_HEIGHT; y++) { var i = ((y * IMAGE_WIDTH) + x); // 16bpp // Generate the next random pixel color value. var value = (short)random.Next(5); bitmapBytes[i] = value; // GRAY } } // Copy the randomized bits to the bitmap pointer. var ptr = bitmapData.Scan0; Marshal.Copy(bitmapBytes,bitmapBytes.Length); // Unlock the bitmap,we're all done. b16bpp.UnlockBits(bitmapData); b16bpp.Save("random.bmp",ImageFormat.Bmp); Debug.WriteLine("saved"); } 我的更改说明: > bitmapData.Stride已经是IMAGE_WIDTH * BytesPerPixel所以你不需要乘以2 总而言之,您尝试将数组8次复制到位图中. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |