validateImageData parameter and Image.FromStream()

前端 未结 4 1535
忘掉有多难
忘掉有多难 2021-02-13 07:12

I\'m concerned about the third parameter in this overload, validateImageData. The documentation doesn\'t explain much about it, it only states that it causes the image data to b

相关标签:
4条回答
  • 2021-02-13 07:38

    From Reflector, we see:

    if (validateImageData)
    {
        num = SafeNativeMethods.Gdip.GdipImageForceValidation(new HandleRef(null, zero));
        if (num != 0)
        {
            SafeNativeMethods.Gdip.GdipDisposeImage(new HandleRef(null, zero));
            throw SafeNativeMethods.Gdip.StatusException(num);
        }
    }
    

    So we see that GdipImageForceValidation is called (recall, System.Drawing is just a wrapper over GDI+). The documentation for this function isn't very good:

    This function forces validation of the image.

    Not very useful. However, the point is made - the image file is interrogated to ensure it is safe to load. This may cause the whole image to be loaded into memory.

    If you are accepting inputs from users, I certainly would set this flag to true - you never know what kind of files (malformed or otherwise) users will upload. Better safe than sorry. This is why the default is true.

    Note also that GDI+ is not recommended for server environments. You're better off using System.Windows.Media.Imaging.

    0 讨论(0)
  • 2021-02-13 07:42

    By perusing inside reflector you'll see that by default .NET always calls a native API in the GDI+ libraries named GdipImageForceValidation (which is by passing true for the validateImageData parameter). I can't find much out about the native API in MSDN, only this, which tells us no more than the name of the function itself. However, it appears that this method causes a performance degradation based on Justin Roger's post about loading images in the fastest possible way via .NET. It is also intuitive to expect that any "validation" step would take away from performance.

    However, if you specify false for the validateImageData parameter, .NET will explicitly trigger an unmanaged code security demand, meaning the framework authors decided that forcing image validation was necessary in order to make the promise of managed code being safe, and ultimately being able to trust the data that the caller says represents an image. So while specifying flase for validateImageData may increase performance, in a less-than-full-trust security context, it may generate an exception, and you had better trust the data you think is an image.

    0 讨论(0)
  • 2021-02-13 07:47

    I remember reading some problems with that parameter. See this post (it's pretty old but just to be carefull).

    0 讨论(0)
  • 2021-02-13 07:47

    Why not just try and see what happens with that flag set and not set?

    In either case you should handle any exceptions that might get thrown.

    0 讨论(0)
提交回复
热议问题