如何将ImageFormat.png传递给BinaryReader [英] How to pass ImageFormat.png to BinaryReader

查看:112
本文介绍了如何将ImageFormat.png传递给BinaryReader的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将rawformat传递给binaryReader,如下所示:



I want to pass rawformat to a binaryReader, like this:

public class ValidateFileAttribute : RequiredAttribute
    {

        public override bool IsValid(object value)
        {
            var ImageProfile = value as byte[];
            if (ImageProfile == null)
            {
                return false;
            }

            if (ImageProfile.Length > 1 * 1024 * 1024)
            {
                return false;
            }

            try
            {
               using (var binaryReader = new BinaryReader(HttpContext.Current.Request.Files[0].InputStream))
                {                    

                    return binaryReader.RawFormat.Equals(ImageFormat.Jpeg);
                }   
            }
            catch { }
            return false;
        }


    }





但在这一行:



But on this line:

return binaryReader.Read(ImageFormat.Png); binaryReader.Read

无法识别。但是如何将Imagaformat.png传递给binaryReader?



谢谢



我试一试像这样:

is not recognised. But how to pass then the Imagaformat.png to the binaryReader?

Thank you

I try it like this:

return binaryReader.RawFormat.Equals(ImageFormat.Jpeg);





或者:



or this:

return binaryReader.ReadBytes(ImageFormat.Png);

推荐答案

你不能只是编造方法,打电话给他们,并期望他们能够工作!



BinaryReader 类用于从流中读取字节。它对图像格式一无所知,也没有提供任何方法来测试它为特定图像格式读取的字节。您需要使用 了解图像格式的类 - 通常是 System.Drawing Bitmap 类c $ c> assembly / namespace。



尝试这样的事情:

You can't just make up methods, call them, and expect them to work!

The BinaryReader class is made to read bytes from a stream. It doesn't know anything about image formats, and it doesn't provide any methods to test the bytes it reads for a particular image format. You need to use a class which does understand image formats - typically the Bitmap class in the System.Drawing assembly/namespace.

Try something like this:
var imageProfile = value as byte[];
if (imageProfile == null)
{
   return false;
}
if (imageProfile.Length == 0)
{
   return false;
}
if (imageProfile.Length > 1 * 1024 * 1024)
{
   return false;
}
if (imageProfile[0] != 0x89)
{
    // PNGs always have the first byte set to 0x89.
    return false;
}

try
{
   using (Stream ms = new MemoryStream(imageProfile))
   using (Image image = Image.FromStream(ms))
   {
      return ImageFormat.Png.Equals(image.RawFormat);
   }
}
catch
{
}

return false;


这篇关于如何将ImageFormat.png传递给BinaryReader的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆