在C#中将图像添加到对象列表

时间:2018-08-15 15:22:07

标签: c#

我正在尝试在C#中创建图像列表。我的问题是我不确定如何引用图像以将其添加到列表中。我尝试在括号中添加文件路径,但是会引发错误“无法创建抽象类或接口'Image'的实例”。以下是我尝试过的示例。

我对此很陌生,因此如果有明显的错误或解决方案,我深表歉意。谢谢! :)

private void button1_Click(object sender, EventArgs e)
{
    imageList = new List<Image>();
    imageOne = new Image("image.jpg");
}

2 个答案:

答案 0 :(得分:3)

Image是一个抽象类。这意味着您不能new

尝试FromFile

imageOne = Image.FromFile("image.jpg");

它返回一个Image对象,您可以将其添加到列表中

答案 1 :(得分:1)

如果要从文件中加载图像,则有FromFile method

msdn中的Ex:

private void Button2_Click(System.Object sender, System.EventArgs e)
{
    try
    {
        Bitmap image1 = (Bitmap) Image.FromFile(@"C:\Documents and Settings\" +
            @"All Users\Documents\My Music\music.bmp", true);

        TextureBrush texture = new TextureBrush(image1);
        texture.WrapMode = System.Drawing.Drawing2D.WrapMode.Tile;
        Graphics formGraphics = this.CreateGraphics();
        formGraphics.FillEllipse(texture, 
            new RectangleF(90.0F, 110.0F, 100, 100));
        formGraphics.Dispose();

    }
    catch(System.IO.FileNotFoundException)
    {
        MessageBox.Show("There was an error opening the bitmap." +
            "Please check the path.");
    }

}

如果要从流中加载图像,也可以使用FromStream method