2017-03-06 103 views
1

我有一個圖像使用轉換器加載到XAML中。我不想再次加載此圖像,我想要拍攝該圖像並找到可用於頁面上其他圖形的主色。到目前爲止,我有這樣的:UWP BitmapImage到Stream

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的畫佳,有什麼我需要在那裏做才能夠實現這一目標?

+0

你在用你提到的轉換器做什麼?你不能同時提取主色嗎? –

+0

對不起,應該澄清它是一個綁定轉換器,從一個id號碼轉換爲圖像源的url –

回答

0

BitmapDecoder要求RandomAccessStream對象創建一個新實例。除非您知道原始來源,否則BitmapImage可能不會被直接提取爲RandomAccessStream。根據你的評論,你是綁定圖像Uri到圖像控件,所以你可以知道原始的源,你可以從BitmapImageUriSource屬性RandomAccessStreamReference類獲得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]); 
} 
+0

謝謝@ sunteen-wu-msft我似乎與此掙扎,因爲每次運行myDominantColour都返回#FF000000無論圖像是什麼 –