Bitmap. fromfile (path)和new Bitmap(path)的区别
本文关键字:Bitmap path 区别 fromfile new | 更新日期: 2023-09-27 18:09:49
我想知道这两者的区别:
Bitmap bitmap1 = new Bitmap("C:''test.bmp");
Bitmap bitmap2 = (Bitmap) Bitmap.FromFile("C:''test.bmp");
一个选项比另一个更好吗?Bitmap.FromFile(path)
填充任何额外的数据到位图图像或它只是一个委托给new Bitmap(path)
?
FromFile方法来自抽象基类Image
,它返回一个Image对象。然而Bitmap
类继承了Image
类,并且Bitmap
构造函数允许你直接初始化Bitmap
对象。
在第二行代码中,您要做的是调用FromFile()
并获得Image
对象,然后将其类型转换为Bitmap
。当位图constructor
可以为您完成时,手动执行此操作并不是一个很好的理由。
两个方法都通过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
;
这些gdip方法导致了两篇MSDN文章(bitmap . tor() &Image.FromFile()),它们彼此非常接近,但是支持的文件格式似乎有所不同:
Bitmap: BMP, GIF, JPEG, PNG, TIFF, Exif, WMF, and EMF
Image: BMP, GIF, JPEG, PNG, TIFF, and EMF.
无论如何,如果你知道你将有位图,我更喜欢new Bitmap("C:''test.bmp")
只是为了摆脱需要转换图像之后。