我想知道这两者之间的区别:
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); }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。