我有一个使用转换器在XAML中加载的图像。而不是再次加载此图像,我想拍摄该图像并找到主导颜色,以便能够用于页面上的其他图形。到目前为止,我有这个:
var himage = (BitmapImage)image_home.Source;
using (var stream = await himage.OpenReadAsync()) //**can't open himage this way**
{
//Create a decoder for the image
var decoder = await BitmapDecoder.CreateAsync(stream);
//Create a transform to get a 1x1 image
var myTransform = new BitmapTransform { ScaledHeight = 1, ScaledWidth = 1 };
//Get the pixel provider
var pixels = await decoder.GetPixelDataAsync(
BitmapPixelFormat.Rgba8,
BitmapAlphaMode.Ignore,
myTransform,
ExifOrientationMode.IgnoreExifOrientation,
ColorManagementMode.DoNotColorManage);
//Get the bytes of the 1x1 scaled image
var bytes = pixels.DetachPixelData();
//read the color
var myDominantColor = Color.FromArgb(255, bytes[0], bytes[1], bytes[2]);
}
显然我无法使用OpenReadAsync打开BitmapImage himage,我需要做些什么才能实现这个目标?
答案 0 :(得分:2)
BitmapDecoder
需要RandomAccessStream
个对象来创建新实例。除非您了解原始来源,否则BitmapImage
可能无法直接提取为RandomAccessStream
。根据您的评论,您将图像Uri绑定到图像控件,这样您就可以知道原始来源,并且可以从RandomAccessStream
的{{3}}属性中获取BitmapImage
根据{{3}}课程,您不需要再次加载图片。代码如下:
var himage = (BitmapImage)image_home.Source;
RandomAccessStreamReference random = RandomAccessStreamReference.CreateFromUri(himage.UriSource);
using (IRandomAccessStream stream = await random.OpenReadAsync())
{
//Create a decoder for the image
var decoder = await BitmapDecoder.CreateAsync(stream);
...
//read the color
var myDominantColor = Color.FromArgb(255, bytes[0], bytes[1], bytes[2]);
}