2

I want a attribute in my Hero class to have a Portrait attribute for his/her image. What object type should I use in this case?

public class Hero
{
    public string Name { get; set; }
    public string HeroType { get; set; }
    public int StartingHP { get; set; }
    public int StartingMana { get; set; }
    public Dictionary<string, string> Spells { get; set; }
    public Dictionary<string, string> Items { get; set; }        
}
Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
Sergio Tapia
  • 40,006
  • 76
  • 183
  • 254

3 Answers3

4

In WPF, you should use the ImageSource class, like this:

public class Hero {
    public string Name { get; set; }
    public string HeroType { get; set; }
    public int StartingHP { get; set; }
    public int StartingMana { get; set; }
    public Dictionary<string, string> Spells { get; set; }
    public Dictionary<string, string> Items { get; set; } 
    public ImageSource Portrait { get; set; }
}

You can read an image from a file like this:

myHero.Portrait = new BitmapImage(new Uri(filePath, UriKind.Absolute));

You can use the Image class from System.Drawing.dll. For example:

public class Hero {
    public string Name { get; set; }
    public string HeroType { get; set; }
    public int StartingHP { get; set; }
    public int StartingMana { get; set; }
    public Dictionary<string, string> Spells { get; set; }
    public Dictionary<string, string> Items { get; set; } 
    public Image Portrait { get; set; }
}

To load the image, call Image.FromFile(path). If you have an image in a stream (eg, from a database or web service, you can call Image.FromStream(stream).

If you have all of the images at compile time, you can put them in a ResX file; you can get an image from the designer-generated code file like this: myHero.Portrait = SomeResXFile.Portrait1.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
3

Beware the memory hogging some of the other answers may lead to. This is a data object right, not a UI object?

Do you know for a fact that you will always need the image for the life of the object? I would be concerned about eating up memory. It's probably better to just keep a resource identifier (file path, name in resource file, etc) and only pass that info on to image boxes. I wouldn't suggest holding on to the whole image. In winforms at least (don't know about WPF) the garbage collector isn't so hot at cleaning up images. It only sees them as a reference (i.e. an integer) because the rest of the image is basically an unmanaged object and thinks it's not a high priority for collection. Meanwhile, it could be chewing up megabytes. We got burned on a previous project of mine on that.

Jim L
  • 2,297
  • 17
  • 20
0

How about this:

System.Drawing.Image

Andy White
  • 86,444
  • 48
  • 176
  • 211