【问题标题】:UWP BitmapImage to StreamUWP 位图图像流式传输
【发布时间】:2017-03-06 22:44:59
【问题描述】:

我有一个使用转换器在 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 图像,我需要在那里做什么才能实现这一点?

【问题讨论】:

  • 你用你提到的转换器做什么?不能同时提取主色吗?
  • 抱歉,应该澄清一下它是一个绑定转换器,可以从 id 号转换为图像源的 url

标签: c# uwp memorystream bitmapimage


【解决方案1】:

BitmapDecoder 需要RandomAccessStream 对象来创建新实例。 BitmapImage 可能不会直接提取为RandomAccessStream,除非您知道原始来源。根据您的评论,您正在将图像 Uri 绑定到图像控件,因此您可以知道原始来源,并且您可以通过RandomAccessStreamReference 类从BitmapImageUriSource 属性中获取RandomAccessStream,您不需要不需要再次加载图像。代码如下:

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

【讨论】:

  • 谢谢@sunteen-wu-msft 我似乎在为此苦苦挣扎,因为每次运行 myDominantColour 无论图像是什么都会返回 #FF000000
猜你喜欢
  • 1970-01-01
  • 2020-12-01
  • 1970-01-01
  • 2015-09-01
  • 2010-10-15
  • 1970-01-01
  • 2018-02-23
  • 2013-01-19
  • 2023-03-21
相关资源
最近更新 更多