我有一些原始传感器数据是单维字节数组。数据实际上是IEEE单精度浮点格式。我知道X和Y轴的长度,我想从我的数据创建一个Windows位图(灰度 - 只有一个包含亮度数据的颜色平面)。
这是我到目前为止所做的:
var bitmap = new Bitmap(xAxis, yAxis, PixelFormat.Format16bppGrayScale);
var pixelReader = GetPixelReader(hdu.MandatoryKeywords.BitsPerPixel);
using (var stream = new MemoryStream(hdu.RawData, writable: false))
{
using (var reader = new BinaryReader(stream, Encoding.ASCII))
{
for (var y = 0; y < yAxis; y++)
{
for (var x = 0; x < xAxis; x++)
{
var pixel = pixelReader(reader);
var argb = Color.FromArgb(pixel, pixel, pixel);
bitmap.SetPixel(x, y, argb);
}
}
}
}
return bitmap;
pixelReader是一个委托,定义为:
private static int ReadIeeeSinglePrecision(BinaryReader reader)
{
return (int) reader.ReadSingle();
}
当我运行此代码时,我在尝试设置像素值的行上得到异常InvalidArgumentException
。我在调试器中调试它,x = 0,y = 0,像素= 0。它没有说哪个参数无效或为什么(感谢Microsoft)。
很明显我做错了,实际上,我怀疑可能有更有效的方法来解决这个问题。我将不胜感激任何建议。由于我无法完全理解的原因,我发现编写代码非常具有挑战性。
答案 0 :(得分:0)
好的,最后是有效的。根据Mark Dawson对此问题的回答代码:https://social.msdn.microsoft.com/Forums/vstudio/en-US/10252c05-c4b6-49dc-b2a3-4c1396e2c3ab/writing-a-16bit-grayscale-image?forum=csharpgeneral
private static Bitmap CreateBitmapFromBytes(byte[] pixelValues, int width, int height)
{
//Create an image that will hold the image data
Bitmap pic = new Bitmap(width, height, PixelFormat.Format16bppGrayScale);
//Get a reference to the images pixel data
Rectangle dimension = new Rectangle(0, 0, pic.Width, pic.Height);
BitmapData picData = pic.LockBits(dimension, ImageLockMode.ReadWrite, pic.PixelFormat);
IntPtr pixelStartAddress = picData.Scan0;
//Copy the pixel data into the bitmap structure
System.Runtime.InteropServices.Marshal.Copy(pixelValues, 0, pixelStartAddress, pixelValues.Length);
pic.UnlockBits(picData);
return pic;
}
然后我修改了自己的代码,将IEEE浮点数据转换为16位整数,然后直接从中创建位图,如下所示:
var pixelReader = GetPixelReader(hdu.MandatoryKeywords.BitsPerPixel);
var imageBytes = new byte[xAxis * yAxis * sizeof(Int16)];
using (var outStream = new MemoryStream(imageBytes, writable: true))
using (var writer = new BinaryWriter(outStream))
using (var inStream = new MemoryStream(hdu.RawData, writable: false))
using (var reader = new BinaryReader(inStream, Encoding.ASCII))
for (var y = 0; y < yAxis; y++)
{
for (var x = 0; x < xAxis; x++)
{
writer.Write(pixelReader(reader));
}
}
var bitmap = CreateGreyscaleBitmapFromBytes(imageBytes, xAxis, yAxis);
return bitmap;
这似乎也解决了评论中强调的效率问题。