我想知道这两者之间的区别:
Bitmap bitmap1 = new Bitmap("C:\\test.bmp");
Bitmap bitmap2 = (Bitmap) Bitmap.FromFile("C:\\test.bmp");
一个选项比另一个更好吗?Bitmap.FromFile(path)
是否向位图图像填充任何其他数据,还是仅作为new Bitmap(path)
的委托?
这两种方法都通过 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);
}
Image.FromFile()
会检查文件是否存在,并在不成立时抛出 FileNotFoundException
。Bitmap.ctor()
在内部调用 GdipCreateBitmapFromFile
,而 Image.FromFile()
调用 GdipLoadImageFromFile
;Bitmap: BMP, GIF, JPEG, PNG, TIFF, Exif, WMF, and EMF
Image: BMP, GIF, JPEG, PNG, TIFF, and EMF.
new Bitmap("C:\\test.bmp")
来摆脱之后需要转换图像的需求。
Image.FromFile
。虽然这并不改变问题。 - lc.