Mat*_*ero 9 c# graphics image bitmap
我想知道这两者之间的区别:
Bitmap bitmap1 = new Bitmap("C:\\test.bmp");
Bitmap bitmap2 = (Bitmap) Bitmap.FromFile("C:\\test.bmp");
Run Code Online (Sandbox Code Playgroud)
一种选择比另一种更好吗?是否Bitmap.FromFile(path)会向位图图像填充任何其他数据,或者它只是一个委托new Bitmap(path)?
小智 6
可通过基类“ Image”(它是抽象类)到“ Bitmap”类使用“ FromFile”方法,并且该方法返回Image对象。其中“ Bitmap”是继承“ Image”类的子类,而Bitmap构造函数允许您直接初始化Bitmap对象。
在您的情况下,您要尝试的是调用FromFile方法并获取一个Image对象,然后将其类型转换为Bitmap。当您让Bitmap构造函数执行此操作时,为什么要执行此操作。Bitmap.FromFile(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;
}
Run Code Online (Sandbox Code Playgroud)
和:
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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18013 次 |
| 最近记录: |