Setting the image property to the file path

I have a human class, as shown below, with the image as an attribute. I'm trying to figure out how to create an instance of the person class in my program class and set the image of the object to the file path, for example. C: \ Users \ Documents \ Picture.jpg. How can i do this?

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; } } 
+4
source share
4 answers

Try the following:

 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); } } 

And create an instance as follows:

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

Using a constructor without parameters will be as follows:

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

Although using a different constructor should be the preferred approach

+1
source

One of the options:

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

Everyone else has already proposed Image.FromFile . You should be aware that this will lock the file, which may cause problems later. More details here:

Why does Image.FromFile sometimes open a file descriptor?

Consider the Image.FromStream method instead. Here is an example of a method that takes a path and returns an image:

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

The value in this approach is that you control when you open and close the file descriptor.

+1
source

Source: https://habr.com/ru/post/1489510/


All Articles