Skip to content

Instantly share code, notes, and snippets.

@tobiasstraub
Created November 5, 2016 06:21
Show Gist options
  • Save tobiasstraub/78dc99ad209d112910fe9f2033aa4ec3 to your computer and use it in GitHub Desktop.
Save tobiasstraub/78dc99ad209d112910fe9f2033aa4ec3 to your computer and use it in GitHub Desktop.
How to get RGB Color from Pixel in UWP
using System;
using System.IO;
using System.Threading.Tasks;
using Windows.Graphics.Imaging;
using Windows.UI;
using Windows.UI.Xaml.Controls;
namespace Bitmap
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
var colorFromPixel1 = Task.Run(async () => await GetColorFromPixel(@"Assets\StoreLogo.png", 1, 1)).Result;
System.Diagnostics.Debug.WriteLine("The color from pixel x1 and y1 is: " + colorFromPixel1);
}
private async Task<Color> GetColorFromPixel(string fileNameOfImage, int xCoordinate, int yCoordinate)
{
var imageFile = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(fileNameOfImage); // Bild laden
var imagestream = await imageFile.OpenStreamForReadAsync(); // Bild in Stream umwandeln
var imageDecoder = await BitmapDecoder.CreateAsync(imagestream.AsRandomAccessStream()); // Stream dekodieren
var imagePixelData = await imageDecoder.GetPixelDataAsync(); // Informationen über Pixel erhalten
var bytes = imagePixelData.DetachPixelData(); // Pixel Daten bekommen
var k = (xCoordinate * (int)imageDecoder.PixelWidth + yCoordinate) * 3; // Navigiere zu entsprechenden Koordinaten
return Color.FromArgb(0, bytes[k + 0], bytes[k + 1], bytes[k + 2]); // Filtere Rot Grün Blau Anteil und wandele dies in Argb um
}
}
}
@GijsZwegers
Copy link

Thanks, helped me a lot!

@qq731574722
Copy link

Thanks a lot. Somehow our bytes are not in same order.
and this worked for me.

var k = (yCoordinate * (int)imageDecoder.PixelWidth + xCoordinate) * 4; 
return Color.FromArgb(bytes[k + 4], bytes[k + 3], bytes[k + 2], bytes[k + 1]); 

@timdetering
Copy link

I suggest adding a using statement enclosing the imagestream object to ensure the stream is closed.

@VinhHV11
Copy link

VinhHV11 commented Dec 1, 2022

imagestream

hi bro, you have code color piker image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment