2013-07-03 49 views
4

我有一个如下图所示的人员类,图像作为属性。我试图弄清楚如何在程序类中创建person类的实例,并将对象的图像设置为文件路径,例如C:\用户\文档\ picture.jpg。我将如何去做这件事?将图像属性设置为文件路径

public class Person 
{ 
    public string firstName { get; set; } 
    public string lastName { get; set; } 
    public Image myImage { get; set; } 

    public Person() 
    { 
    } 

    public Person(string firstName, string lastName, Image image) 
    { 
     this.fName = firstName; 
     this.lName = lastName; 
     this.myImage = image; 
    } 
} 
+2

'myImage'的类型是'Image'而不是'String',那么你想在哪里存储文件路径?或者你是否想相应地改变这个属性的类型? –

回答

1

试试看这个:

public class Person 
{ 
    public string firstName { get; set; } 
    public string lastName { get; set; } 
    public Image myImage { get; set; } 
    public Person() 
    { 
    } 
    public Person(string firstName, string lastName, string imagePath) 
    { 
     this.fName = firstName; 
     this.lName = lastName; 
     this.myImage = Image.FromFile(imagePath); 
    } 
} 

和实例是这样的:

Person p = new Person("John","Doe",@"C:\Users\Documents\picture.jpg"); 
+0

这正是我期待的,非常感谢! – bookthief

1

使用您的无参数的构造函数,将如下:

Person person = new Person(); 
Image newImage = Image.FromFile(@"C:\Users\Documents\picture.jpg"); 
person.myImage = newImage; 

虽然使用其他的构造应该是首选的方法

+0

谢谢,但是我需要导入程序类中的任何名称空间来执行此操作吗?我有System.Drawing,但Image中没有列出FromFile选项。 – bookthief

+0

'FromFile'是[Image Class](http://msdn.microsoft.com/en-us/library/system.drawing.image.aspx)的一部分。你的项目中是否有名为'Image'的其他类? – Liel

1

一个办法是这样的:

public Person(string firstName, string lastName, string imagePath) 
{ 
    ... 
    this.myImage = Image.FromFile(imagePath); 
} 
1

其他人已经建议Image.FromFile。你应该知道这会锁定文件,这可能会在稍后导致问题。更多阅读这里:

Why does Image.FromFile keep a file handle open sometimes?

考虑使用Image.FromStream方法来代替。这里有一个例子方法,它的路径,并返回一个图像:

private static Image GetImage(string path) 
{ 
    Image image; 
    using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read)) 
    { 
     image = Image.FromStream(fs); 
    } 
    return image; 
} 

这种方法的价值是你控制当您打开和关闭文件句柄。

相关问题