Corey Thompson
Corey Thompson

Reputation: 398

Converting string into new Image XAML C#

I've got a string of a location for an image, and I'm trying to create a XAML Image object, change the source to the string, and append it to a stackpanel.

Here's what I've tried so far:

System.Windows.Media.Imaging.BitmapImage tmp = new System.Windows.Media.Imaging.BitmapImage();
tmp.UriSource = new Uri("Assets/image.jpg", UriKind.RelativeOrAbsolute);
Image image = new Image();
image.Source = tmp;

The problem is that I can't seem to convert System.Windows.Media.Imaging.BitmapImage to Windows.UI.Xaml.Media.ImageSource.

I'm using that code pretty much directly off the Microsoft MSDN website, and I can't understand why it's not working. I've also tried creating an ImageSource object and I just can't seem to get anything to work. It's frustrating.

Upvotes: 0

Views: 908

Answers (3)

Rohit Vats
Rohit Vats

Reputation: 81253

The problem is that I can't seem to convert System.Windows.Media.Imaging.BitmapImage to Windows.UI.Xaml.Media.ImageSource.

As per ImageSource reference it seems you are using WinRT app and not WPF.

You should use Windows.UI.Xaml.Media.Imaging.BitmapImage if you are targeting WinRT app. System.Windows.Media.Imaging.BitmapImage meant to be used from WPF.

Upvotes: 1

sexta13
sexta13

Reputation: 1568

You also can try this:

BitmapImage BitmapToImageSource(System.Drawing.Bitmap bitmap, System.Drawing.Imaging.ImageFormat imgFormat)
        {
            using (MemoryStream memory = new MemoryStream())
            {
                bitmap.Save(memory, imgFormat);
                memory.Position = 0;
                BitmapImage bitmapImage = new BitmapImage();
                bitmapImage.BeginInit();
                bitmapImage.StreamSource = memory;
                bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                bitmapImage.EndInit();

                return bitmapImage;
            }
        }

(source: http://pastebin.com/PAJ7Cd0x)

Regards,

Upvotes: 0

Sheridan
Sheridan

Reputation: 69959

Displaying Images from string file paths is easy in WPF. First, ensure that the files have been added into the project using Visual Studio's Add Existing Item command so that it adds the image files with a Build Action value of Resource. Next, you need to use the correct file path. It is best if you refer to the Pack URIs in WPF page on MSDN for full details, but you can use this format pretty much everywhere in your application:

pack://application:,,,/ProjectOrAssemblyName;component/SubFolderName/ImageName.png

To display that image, you can simply set that value to a string property and data bind it to an Image.Source property in the UI, or use it directly:

<Image Source="{Binding YourImageSource}" />

...

<Image Source="pack://application:,,,/
    ProjectOrAssemblyName;component/SubFolderName/ImageName.png" />

Upvotes: 2

Related Questions