在使用StorageFile读取图像之前,先使用StorageFile获取位图尺寸
本文关键字:StorageFile 获取 位图 读取 图像 | 更新日期: 2023-09-27 18:14:39
好的,我正在尝试在WPF应用程序中分析图像的启发式。当用户选择图像文件位置时,我想在代码后打开图像,检查图像的颜色,并将其输出到应用程序中。然而,为了正确检查图像的像素,我需要获得将其加载到可以获得像素颜色的WriteableBitmap
的尺寸。
当我打开一个流文件第二次应用程序只是挂起。下面是代码:
private static async Task<Dictionary<Color, int>> GetColorCountsAsync(string path)
{
var colorCounts = new Dictionary<Color, int>();
var absolutePath = string.Format(@"{0}'{1}",Directory.GetCurrentDirectory(),path);
var dimension = await GetBitmapDimensions(absolutePath); //Method below - opens via StorageFile
var file = await StorageFile.GetFileFromPathAsync(absolutePath); //Hangs forever
using (var stream = await file.OpenStreamForReadAsync().ConfigureAwait(false))
{
var pixelWidth = dimension.Width;
var pixelHeight = dimension.Height;
var bitmap = new WriteableBitmap(pixelWidth, pixelHeight);
bitmap.SetSource(stream.AsRandomAccessStream());
using (var buffer = bitmap.PixelBuffer.AsStream())
{
var pixels = new byte[4 * pixelWidth * pixelHeight];
buffer.Read(pixels, 0, pixels.Length);
for (var y = 0; y < pixelHeight; y++)
{
for (var x = 0; x < pixelWidth; x++)
{
var index = ((y * pixelWidth) + x) * 4;
var alpha = pixels[index + 4];
var red = pixels[index + 2];
var green = pixels[index + 1];
var blue = pixels[index + 0];
var color = Color.FromArgb(alpha, red, green, blue);
if (!colorCounts.ContainsKey(color))
{
colorCounts.Add(color, 0);
}
colorCounts[color] = colorCounts[color] + 1;
}
}
}
}
return colorCounts;
}
private static async Task<Dimension> GetBitmapDimensions(string absolutePath)
{
var file = await StorageFile.GetFileFromPathAsync(absolutePath);
var bitmapImage = new BitmapImage();
using (var fileStream = await file.OpenAsync(FileAccessMode.Read))
{
bitmapImage.SetSource(fileStream);
}
return new Dimension { Height = bitmapImage.PixelHeight, Width = bitmapImage.PixelWidth };
}
我不能关闭位图图像也不能处理它-是什么导致应用程序冻结?
您不需要正确尺寸的位图,因为SetStream()
是一种扩展方法。它只需要一个对象,像这样调用它:
var bitmap = new WriteableBitmap(1,1).SetSource(stream.AsRandomAccessStream());