Bitmap.FromFile(路径)和新位图(路径)之间的区别

时间:2015-08-25 14:52:52

标签: c# image graphics bitmap

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

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

一种选择比另一种更好吗? Bitmap.FromFile(path)是否会向位图图片填充任何其他数据,或者它只是new Bitmap(path)的委托?

3 个答案:

答案 0 :(得分:3)

两种方法都通过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 :(得分:3)

' FROMFILE'方法可以通过基类' Image'(这是一个抽象类)到' Bitmap' class,它返回一个Image对象。在哪里作为' Bitmap'是继承' Image' class和Bitmap构造函数允许您直接初始化Bitmap对象。

在您的情况下,您要尝试的是调用FromFile方法并获取Image对象,然后键入将其转换为Bitmap。为什么在使用Bitmap构造函数执行此操作时执行此操作。 Bitmap.FromFile(path)是否向位图图像填充任何其他数据: 否

答案 2 :(得分:1)

很难说 - 内部两种方法都非常接近,除了Image.FromFile()将检查文件是否存在,如果不是这样,则抛出FileNotFoundException

主要区别在于Bitmap.ctor()内部调用GdipCreateBitmapFromFileImage.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.

无论如何,如果你知道你会有Bitmap,我更喜欢new Bitmap("C:\\test.bmp")只是为了摆脱之后投射图像的需要。