c# – Bitmap.FromFile(路径)和新位图(路径)之间的差异

前端之家收集整理的这篇文章主要介绍了c# – Bitmap.FromFile(路径)和新位图(路径)之间的差异前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想知道这两者之间的区别:
  1. Bitmap bitmap1 = new Bitmap("C:\\test.bmp");
  2. Bitmap bitmap2 = (Bitmap) Bitmap.FromFile("C:\\test.bmp");

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

解决方法

两种方法都通过path参数获取图像句柄. Image.FromFile将返回超类Image,而前者只返回Bitmap,因此您可以避免强制转换.

在内部,他们几乎都这样做:

  1. public static Image FromFile(String filename,bool useEmbeddedColorManagement)
  2. {
  3.  
  4. if (!File.Exists(filename))
  5. {
  6. IntSecurity.DemandReadFileIO(filename);
  7. throw new FileNotFoundException(filename);
  8. }
  9.  
  10. filename = Path.GetFullPath(filename);
  11.  
  12. IntPtr image = IntPtr.Zero;
  13. int status;
  14.  
  15. if (useEmbeddedColorManagement)
  16. {
  17. status = SafeNativeMethods.Gdip.GdipLoadImageFromFileICM(filename,out image);
  18. }
  19. else
  20. {
  21. status = SafeNativeMethods.Gdip.GdipLoadImageFromFile(filename,out image);
  22. }
  23.  
  24. if (status != SafeNativeMethods.Gdip.Ok)
  25. throw SafeNativeMethods.Gdip.StatusException(status);
  26.  
  27. status = SafeNativeMethods.Gdip.GdipImageForceValidation(new HandleRef(null,image));
  28.  
  29. if (status != SafeNativeMethods.Gdip.Ok)
  30. {
  31. SafeNativeMethods.Gdip.GdipDisposeImage(new HandleRef(null,image));
  32. throw SafeNativeMethods.Gdip.StatusException(status);
  33. }
  34.  
  35. Image img = CreateImageObject(image);
  36. EnsureSave(img,filename,null);
  37.  
  38. return img;
  39. }

和:

  1. public Bitmap(String filename)
  2. {
  3. IntSecurity.DemandReadFileIO(filename);
  4. filename = Path.GetFullPath(filename);
  5.  
  6. IntPtr bitmap = IntPtr.Zero;
  7.  
  8. int status = SafeNativeMethods.Gdip.GdipCreateBitmapFromFile(filename,out bitmap);
  9.  
  10. if (status != SafeNativeMethods.Gdip.Ok)
  11. throw SafeNativeMethods.Gdip.StatusException(status);
  12.  
  13. status = SafeNativeMethods.Gdip.GdipImageForceValidation(new HandleRef(null,bitmap));
  14.  
  15. if (status != SafeNativeMethods.Gdip.Ok)
  16. {
  17. SafeNativeMethods.Gdip.GdipDisposeImage(new HandleRef(null,bitmap));
  18. throw SafeNativeMethods.Gdip.StatusException(status);
  19. }
  20.  
  21. SetNativeImage(bitmap);
  22.  
  23. EnsureSave(this,null);
  24. }

猜你在找的C#相关文章