UWP BitmapImage to Stream

时间:2017-03-06 22:45:00

标签: c# uwp memorystream bitmapimage

我有一个使用转换器在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,我需要做些什么才能实现这个目标?

1 个答案:

答案 0 :(得分:2)

BitmapDecoder需要RandomAccessStream个对象来创建新实例。除非您了解原始来源,否则BitmapImage可能无法直接提取为RandomAccessStream。根据您的评论,您将图像Uri绑定到图像控件,这样您就可以知道原始来源,并且可以从RandomAccessStream的{​​{3}}属性中获取BitmapImage根据{{​​3}}课程,您不需要再次加载图片。代码如下:

 var himage = (BitmapImage)image_home.Source;
 RandomAccessStreamReference random = RandomAccessStreamReference.CreateFromUri(himage.UriSour‌​ce);

 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]);
 }