Associate Bitmapimge with image in Wpf?

This is a simple question (let's see)

I want to associate a bitmap with an image. To do this, cs u must write this line in the code.

this.leftImage.Source = new BitmapImage(new Uri(@"C:\a.bmp"));

But I want to make a binding from resources. Since at the time of release the resources were part of the project.exe file, and if you are linking from a file (Average Image.source with the address of the image file), you should always put the image file in the same address (emergency recovery program) :)

+1
source share
1 answer

One option is to get it from a resx file. You can do something like this. Assuming Images.resx contains a Left image bitmap.

leftImage.Source = ConvertBitmapToBitmapImage(Images.Left);
...
private BitmapImage ConvertBitmapToBitmapImage(Bitmap bitmap)
{
  MemoryStream memoryStream = new MemoryStream();
  bitmap.Save(memoryStream, ImageFormat.Png);
  BitmapImage bitmapImage = new BitmapImage();
  bitmapImage.BeginInit();
  bitmapImage.StreamSource = new MemoryStream(memoryStream.ToArray());
  bitmapImage.EndInit();

  return bitmapImage;
}

With extra work, you can also do this from XAML.

+2

Source: https://habr.com/ru/post/1747709/


All Articles