Hi,@Paolo Mossa. Welcome to Microsoft Q&A.
To retrieve the pixels of an image drawn on a Canvas in WPF, you could follow following sample:
Use the Bitmap's GetPixel() method to retrieve the pixels.
<StackPanel>
<Canvas Background="LightGreen" Height="380">
<Canvas x:Name="canvas" Background="AliceBlue" Width="300" Height="200">
</Canvas>
</Canvas>
<Button Content="click" Click="Button_Click"/>
</StackPanel>
Codebehind:
using System.Drawing;
using System.IO;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Color = System.Drawing.Color;
using Size = System.Windows.Size;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
int x = 100;
int y = 50;
private void Button_Click(object sender, RoutedEventArgs e)
{
Size canvasSize = new Size(canvas.ActualWidth, canvas.ActualHeight);
RenderTargetBitmap renderBitmap = new RenderTargetBitmap((int)canvasSize.Width, (int)canvasSize.Height, 96, 96, PixelFormats.Default);
// Render the Canvas content onto the render target bitmap
renderBitmap.Render(canvas);
// Convert the render target bitmap to a Bitmap
BitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
using (MemoryStream ms = new MemoryStream())
{
encoder.Save(ms);
Bitmap bitmap = new Bitmap(ms);
if (x >= 0 && x < bitmap.Width && y >= 0 && y < bitmap.Height)
{
Color pixelColor = bitmap.GetPixel(x, y);
MessageBox.Show($"Color at ({x}, {y}): R={pixelColor.R}, G={pixelColor.G}, B={pixelColor.B}");
}
else
{
MessageBox.Show("Coordinates are out of bounds.");
}
}
}
}
The result:
Colot at(100,50):R=240,G=248,B=255
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.