-3

I have to add image to my label, but I can't find solution how to do this. I'm trying by use this:

        InitializeComponent();
        url = Directory.GetCurrentDirectory() + @"/Cards/cardSkin.png";
        mylabel.Background = new ImageBrush(new BitmapImage(new Uri(url)));

I don't know even if I'm using this right, I just copied this from others project what we did with class. Anyway, I tried to create Image img = Image.FromFile("YourFile.bmp"); but I don't why, .FromFile wasn't working for me. Anyone of you guys have the other way to make label as picture(background) and help newbie do this? :D

Thrown Exception:

Error 1 'System.Windows.Controls.Image' does not contain a definition for 'FromFile.
varg
  • 3,446
  • 1
  • 15
  • 17
herblack
  • 31
  • 1
  • 1
  • 2
  • What's the code for?What kind of label it is (winform, wpf, silverlight)? What are you trying to do and what's the problem except "not working"? – xing Oct 11 '12 at 20:59
  • 1
    Well, it didn't work, because there are different Image classes in .NET. You've tried to use a method from System.Drawing.Image on System.Windows.Controls.Image. I don't know anything about Windows Forms, but take a look at http://msdn.microsoft.com/en-gb/library/gg145045.aspx - it's the best source of knowledge about API. – Piotr Zierhoffer Oct 11 '12 at 21:01
  • It's wpf label. Im doing the 21 game (blackjack) and I have to make label as card picture. Im trying to create Image class, but FromFile doesn't work. – herblack Oct 11 '12 at 21:03
  • Possible duplicate of [C# Adding Image to a Label](https://stackoverflow.com/questions/23891155/c-sharp-adding-image-to-a-label) – Carl Walsh Nov 08 '17 at 09:23

2 Answers2

7

This works for me:

Label ilabel = new Label(); // create a label
Image i = Image.FromFile("image.png"); // read in image
ilabel.Size = new Size(i.Width, i.Height); //set label to correct size
ilabel.Image = i; // put image on label
this.Controls.Add(ilabel); // add label to container (a form, for instance)
Engineer
  • 834
  • 1
  • 13
  • 27
  • Note: I found a Label to be inadequate and soon switched to a Button, because I wanted the OnClick event. – Engineer Oct 28 '20 at 00:16
1

If you're using a Label created in the Form designer, make sure to set AutoSize to false. Otherwise the .Width will be 0 because the text is empty and modifying the .Size is ignored.

Code like this will work:

label1.Image?.Dispose(); // prevent memory leak
var image = Image.FromFile(@"image.png");
label1.Size = image.Size;
label1.Image = image;
Carl Walsh
  • 6,100
  • 2
  • 46
  • 50