我想知道这两者之间的区别:
Bitmap bitmap1 = new Bitmap("C:\\test.bmp"); Bitmap bitmap2 = (Bitmap) Bitmap.FromFile("C:\\test.bmp");
一种选择比另一种更好吗? Bitmap.FromFile(path)是否会向位图图像填充任何其他数据,或者它只是新Bitmap(路径)的委托?
解决方法
两种方法都通过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,null); }