Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading a picture file Image.FromFile VS FileStream

I must admit that I never understood what are the streams are all about- I always thought it's an internet thing. But now I run into a code that used a stream to load a file localy and I wonder if there is advantage for using a stream over... well the way I always loaded files:

private void loadingfromStream()
{
   DirectoryInfo dirInfo = new DirectoryInfo("c:/");
   FileInfo[] fileInfoArr = dirInfo.GetFiles();
   FileInfo fileInfo = fileInfoArr[0];       

   // creating a bitmap from a stream
   FileStream fileStream = fileInfo.OpenRead();            
   Bitmap bitmap = new Bitmap(fileStream);  
   Image currentPicture = (Image)bitmap       
}

vs.

private void loadingUsingImageClass
{    
   Image currentPicture = Image.FromFile(originalPath);
}
like image 527
Asaf Avatar asked Aug 20 '10 09:08

Asaf


2 Answers

If you know your code will be loading the data from a file, use Image.FromFile - it's obviously rather simpler code, and it's just possible that there are optimizations within the framework when it's dealing with files.

Using a stream is more flexible, but unless you need that flexibility, go with the file solution.

like image 86
Jon Skeet Avatar answered Oct 16 '22 09:10

Jon Skeet


If you want to deal with image files, of course the second solution is better. In your first section, you have Bitmap bitmap = new Bitmap(fileStream); you know that an image file is not always Bitmap, it also can be JPEG/PNG/TIFF and so on. While Image.FromFile is quite professional to deal with image files with different extensions.

Generally speaking, FileStream is common at file issues, while Image.FromFile is more particular at image files. It depends on what kind of files you are going to deal with.

like image 30
Cheng Chen Avatar answered Oct 16 '22 10:10

Cheng Chen