Loading a picture file Image.FromFile VS FileStream

自闭症网瘾萝莉.ら 提交于 2019-11-29 10:37:21

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.

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.

As an a addition to Jon´s answer:

As far as I see, the two methods don't do the same thing either. The first is given you the first image in "C:\" where the second just give you a image from a path. So the added complexity in the first is not just because it is using streams.

This would be equivalent:

using (var fs = File.OpenRead(path))
using (var img = Image.FromStream(fs))
{
    //...
}

and in that case, it is certainly better to just do it with Image.FromFile as Jon explained.

Well, a file is often treated as a stream as well. That's why the primary class to open files is called FileStream. But there's a specific operating system feature that can make dealing with image files a lot more efficient. It is called 'memory mapped files', a feature that maps the content of a file directly to memory. There's some smoke and mirrors involved, but it essentially makes the file directly available without having to read it. The memory you need to store the file data doesn't take space in the paging file.

Very efficient, you'll get it for free when you use FromFile() or the Bitmap(string) constructor for an image in the .bmp format. Loading an image from a stream tends to require twice the amount of memory, always a problem with big images.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!