tags:

views:

28

answers:

1

Hi all,

Ok firstly this is probably going to sound like a weird thing that I am trying to do, but please bare with me :)

I have instantiated several System.Drawing.Icon Objects. Note that these are created at runtime and are not stored and loaded from the file system. I would like to place these images in my WPF application.

However as I have discovered over the last few hours (Yes I have been at this for a while now ^^) it is not possible to simply add an object such as an system.drawing.image or icon directly to the canvas/stack panel nor is it possible to set the source of a System.Windows.Controls.Image to an image or icon not stored within the file system (or so it seems to me).

Any ideas?

Starting to go a bit nuts on this one. :D

+1  A: 

This has worked for me dynamically setting a WPF Image with bytes loaded from a bitmap that was either dynamically generated or loaded from disk:

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using System.IO;
using System.Drawing.Imaging;

namespace Examples
{
    public class Util
    {
        private static void SetBitmap(Image imgDest, Bitmap bmpSource)
        {
            byte[] imageBytes;
            using (MemoryStream stream = new MemoryStream())
            {
                bmpSource.Save(stream, ImageFormat.Png);

                imageBytes = stream.ToArray();
            }

            BitmapImage bitmapImage = new BitmapImage();
            bitmapImage.BeginInit();
            bitmapImage.StreamSource = new MemoryStream(imageBytes);
            bitmapImage.EndInit();

            imgDest.Source = bitmapImage;
        }
    }
}
David
Hi David, Thanks yes I tried something similar earlier but got a "Error HRESULT E_FAIL has been returned from a call to a COM component." when trying "bmpSource.Save"
Jambobond
Got it Working, I had to add my Icons to an good old-fashioned System.Windows.Forms.ImageList() first
Jambobond