I have a simple method which call a function that returns a bitmap
image.
private void ImageToGrayScale(object sender, RoutedEventArgs e)
{
pbStatus.Visibility = Visibility.Visible;
if (loadedImage != null)
{
new Thread(() =>
{
BitmapImage bitmapImage= ThreadProcedure();
this.Dispatcher.Invoke(new Action(()=> {
pbStatus.Visibility = Visibility.Hidden;
EditedImage.Source = bitmapImage;
}));
}).Start();
}
else
{
MessageBox.Show("Please select the image first!");
}
}
Everytime at line: EditedImage.Source = bitmapImage;
a get an error:
The calling thread cannot access this object because a different thread owns it.
Also, here is the method which returns a bitmap
image.
private BitmapImage ThreadProcedure()
{
Bitmap editedImage = new Bitmap(loadedImage);
for (int x = 0; x < editedImage.Width; x++)
{
for (int y = 0; y < editedImage.Height; y++)
{
Color pixelColor = editedImage.GetPixel(x, y);
int rgb = (int)((pixelColor.R + pixelColor.G + pixelColor.B) / 3);
editedImage.SetPixel(x, y, Color.FromArgb(rgb, rgb, rgb)); // Now greyscale
}
}
return Converter.ConvertBitmapToBitmapImage(editedImage, extension);
}