加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 08:29:37 所属栏目:百科 来源:网络整理
导读:我想知道这两者之间的区别: Bitmap bitmap1 = new Bitmap("C:test.bmp");Bitmap bitmap2 = (Bitmap) Bitmap.FromFile("C:test.bmp"); 一种选择比另一种更好吗? Bitmap.FromFile(path)是否会向位图图像填充任何其他数据,或者它只是新Bitmap(路径)的委托
我想知道这两者之间的区别:
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);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读