Bitmap.FromFile(path)和new Bitmap(path)之间的区别

16

我想知道这两者之间的区别:

Bitmap bitmap1 = new Bitmap("C:\\test.bmp");
Bitmap bitmap2 = (Bitmap) Bitmap.FromFile("C:\\test.bmp");

一个选项比另一个更好吗?Bitmap.FromFile(path)是否向位图图像填充任何其他数据,还是仅作为new Bitmap(path)的委托?


1
就你所知,你正在从派生类中调用一个静态方法,实际上是 Image.FromFile。虽然这并不改变问题。 - lc.
3个回答

11
'FromFile'方法来自抽象基类'Image',它返回一个Image对象。而'Bitmap'类继承了'Image'类,并且'Bitmap'构造函数允许您直接初始化'Bitmap'对象。
在您的第二行代码中,您正在尝试调用'FromFile()'并获取一个'Image'对象,然后将其强制转换为'Bitmap'。手动这样做没有很好的原因,因为位图'构造函数'可以为您完成此操作。

4

这两种方法都通过 path参数获取图像的句柄。 Image.FromFile返回超类Image,而前者则仅返回Bitmap,您可以避免转换。

在内部,它们基本相同:

public static Image FromFile(String filename,
                                     bool useEmbeddedColorManagement)
{

    if (!File.Exists(filename)) 
    {
        IntSecurity.DemandReadFileIO(filename);
        throw new FileNotFoundException(filename);
    }

    filename = Path.GetFullPath(filename);

    IntPtr image = IntPtr.Zero;
    int status;

    if (useEmbeddedColorManagement) 
    {
        status = SafeNativeMethods.Gdip.GdipLoadImageFromFileICM(filename, out image);
    }
    else 
    {
        status = SafeNativeMethods.Gdip.GdipLoadImageFromFile(filename, out image);
    }

    if (status != SafeNativeMethods.Gdip.Ok)
        throw SafeNativeMethods.Gdip.StatusException(status);

    status = SafeNativeMethods.Gdip.GdipImageForceValidation(new HandleRef(null, image));

    if (status != SafeNativeMethods.Gdip.Ok)
    {
        SafeNativeMethods.Gdip.GdipDisposeImage(new HandleRef(null, image));
        throw SafeNativeMethods.Gdip.StatusException(status);
    }

    Image img = CreateImageObject(image);
    EnsureSave(img, filename, null);

    return img;
}

同时:

public Bitmap(String filename) 
{
    IntSecurity.DemandReadFileIO(filename);
    filename = Path.GetFullPath(filename);

    IntPtr bitmap = IntPtr.Zero;

    int status = SafeNativeMethods.Gdip.GdipCreateBitmapFromFile(filename, out bitmap);

    if (status != SafeNativeMethods.Gdip.Ok)
        throw SafeNativeMethods.Gdip.StatusException(status);

    status = SafeNativeMethods.Gdip.GdipImageForceValidation(new HandleRef(null, bitmap));

    if (status != SafeNativeMethods.Gdip.Ok) 
    {
        SafeNativeMethods.Gdip.GdipDisposeImage(new HandleRef(null, bitmap));
        throw SafeNativeMethods.Gdip.StatusException(status);
    }

    SetNativeImage(bitmap);

    EnsureSave(this, filename, null);
}

1
很难说-在内部,这两种方法非常接近,除了 Image.FromFile() 会检查文件是否存在,并在不成立时抛出 FileNotFoundException
主要区别在于 Bitmap.ctor() 在内部调用 GdipCreateBitmapFromFile,而 Image.FromFile() 调用 GdipLoadImageFromFile
这些 Gdip 方法导致了两篇 MSDN 文章 (Bitmap.ctor() & Image.FromFile()),它们非常相似,但支持的文件格式似乎有所不同:
Bitmap: BMP, GIF, JPEG, PNG, TIFF, Exif, WMF, and EMF
Image:  BMP, GIF, JPEG, PNG, TIFF, and EMF.

无论如何,如果您知道将要使用位图,我更喜欢使用new Bitmap("C:\\test.bmp")来摆脱之后需要转换图像的需求。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接