簡體   English   中英

UWP BitmapImage to Stream

[英]UWP BitmapImage to Stream

我有一個使用轉換器在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,我需要做什么才能實現這一點?

BitmapDecoder需要RandomAccessStream對象來創建新實例。 除非您知道原始源,否則BitmapImage可能無法直接提取為RandomAccessStream 根據您的意見,您有約束力圖像烏里圖像控件,所以你可以知道原始出處和你可以得到RandomAccessStreamBitmapImageUriSource地產RandomAccessStreamReference類,則不需要再次加載圖片。 代碼如下:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM