0

I've created Image object in xaml code:

<Image Name="Square" Source="Square.png" Height="400" Width="640"/>

In code-behind I've written:

WriteableBitmap bitmap = new WriteableBitmap((int)Square.Width, (int)Square.Height, 96, 96, PixelFormats.Rgb24, null);

If I'm creating pixel array, puting to WritableBitmap and then to Image like this:

    int width = 300;
    int height = 300;
    WriteableBitmap bitmap = new WriteableBitmap(width, height, 96, 96, PixelFormats.Rgb24, null);
    uint[] pixels = new uint[width * height];

    bitmap.WritePixels(new Int32Rect(0, 0, 300, 300), pixels, width * 4, 0);
    **Square.Source = bitmap;**

I haven't any problem, but when I'm trying to load my image created in xaml code to WritableBitmap, I can't do this:

WriteableBitmap bitmap = new WriteableBitmap((int)Square.Width, (int)Square.Height, 96, 96, PixelFormats.Rgb24, null);
bitmap = Square.Source; // Cannot implicitly convert type 'System.Windows.Media.ImageSource' to 'System.Windows.Media.Imaging.WriteableBitmap'

So if I can't convert type 'System.Windows.Media.ImageSource' to 'System.Windows.Media.Imaging.WriteableBitmap', why I can convert 'System.Windows.Media.Imaging.WriteableBitmap' to 'System.Windows.Media.ImageSource'?

    Square.Source = bitmap;
    bitmap = Square.Source; // Why it does not work?

Thanks for any help.

wsc
  • 50
  • 1
  • 8
  • Have you tried something like this?: `WriteableBitmap writeableBitmap = new WriteableBitmap(Square.Source);` – Sheridan Sep 24 '14 at 09:53
  • Hi Sheridan, I've put your code in visual but I have to errors: *The best overloaded method match for 'System.Windows.Media.Imaging.WriteableBitmap.WriteableBitmap(System.Windows.Media.Imaging.BitmapSource)' has some invalid arguments* **and** *Argument 1: cannot convert from 'System.Windows.Media.ImageSource' to 'System.Windows.Media.Imaging.BitmapSource'* – wsc Sep 24 '14 at 09:55
  • Ahh sorry, I forgot to cast the `ImageSource` to a `BitmapSource`. See @Clemens' answer. – Sheridan Sep 24 '14 at 10:13

1 Answers1

2

You can't directly create a WriteableBitmap from any ImageSource, because the ImageSource might not be a BitmapSource (which is what the Writeablebitmap constructor takes as argument).

However, in your case it is safe to cast the Source property to BitmapSource:

var bitmap = new WriteableBitmap((BitmapSource)Square.Source);

Note that the Source property of Image control is of type ImageSource (and not BitmapSource) because the control is able to display other types of images than only bitmaps, e.g. vector images.

Clemens
  • 123,504
  • 12
  • 155
  • 268