C# 如何将图像添加到标签?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12848341/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:40:47  来源:igfitidea点击:

How do I add an image to a label?

c#imagelabelfromfile

提问by herblack

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, .FromFilewasn't working for me. Anyone of you guys have the other way to make label as picture(background) and help newbie do this? :D

我不知道我是否正确使用了这个,我只是从其他项目中复制了我们在课堂上所做的事情。无论如何,我试图创造,Image img = Image.FromFile("YourFile.bmp");但我不知道为什么,.FromFile对我不起作用。你们中的任何人都有另一种方法将标签制作为图片(背景)并帮助新手做到这一点?:D

Thrown Exception:

抛出异常:

Error 1 'System.Windows.Controls.Image' does not contain a definition for 'FromFile.

回答by codingbiz

Try this

尝试这个

Image img = System.Drawing.Bitmap.FromFile(filename);

回答by Engineer

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)

回答by Carl Walsh

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

如果您使用的是在表单设计器中创建的标签,请确保设置AutoSize为 false。否则.Width将是 0,因为文本是空的,修改 将.Size被忽略。

Code like this will work:

像这样的代码将起作用:

label1.Image?.Dispose(); // prevent memory leak
var image = Image.FromFile(@"image.png");
label1.Size = image.Size;
label1.Image = image;