我有一个关于 BitmapSource.Create 的问题。我有以下代码,但它的行为不符合预期:
reader.BaseStream.Position += BytesInMetadata;
var rawData = new UInt16[NumberOfPixels];
// Read in the raw image data in 16 bit format.
NumberOfPixels.Times((Action<int>)(i => rawData[i] = reader.ReadUInt16()));
var stats = new MsiStats()
{
Mean = rawData.Average(v => (Double)v),
StdDev = rawData.StandardDeviation(v => (Double)v),
Min = rawData.Min(),
Max = rawData.Max()
};
// Convert the 16-bit image to an 8-bit image that can actually be displayed.
var scaledData = ScaleData(rawData, 4.0f, CType);
GCHandle handle = GCHandle.Alloc(scaledData, GCHandleType.Pinned);
using (var bmp = new Bitmap(2048, 2048, 2048, System.Drawing.Imaging.PixelFormat.Format8bppIndexed, handle.AddrOfPinnedObject()))
{
bmp.Save(@"C:\Users\icyr\Work Folders\COBRA_I-3\CAST Data\myOGBitmap.bmp");
}
handle.Free();
var src = BitmapSource.Create(NumberOfColumns, NumberOfRows,
96, 96,
PixelFormats.Gray8, null,
scaledData,
NumberOfRows);
using (var fileStream = new FileStream(@"C:\<somefolder>\myBitmap.bmp", FileMode.OpenOrCreate))
{
BitmapEncoder enc = new BmpBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(src));
enc.Save(fileStream);
}
我正在从专有图像文件中读取 12 位值,将其转换为 8 位,然后将其保存为位图源对象。但是,当我读回它(或保存它,如下所示)时,它会保存它......错误。我什至不知道如何描述它。当我在 Matlab 中读取保存的图像时,从 Bitmapsource 对象保存的文件只有 17 的倍数的像素值。从 scaledData 对象保存的文件具有完整的值范围。
这里发生了什么?不幸的是,我正在一个我没有编写的代码框架内工作,除非我想彻底检查整个项目(我没有,也没有时间),否则我需要继续能够使用用于我的数据存储目的的 BitmapSource 对象。
我不知道该怎么做,所以我希望你们能更好地理解为什么会发生这种情况,以及如何通过最小的改变来防止它发生。