美文网首页
C# 关于 读取图片转字节,发现数组少字节问题

C# 关于 读取图片转字节,发现数组少字节问题

作者: 令狐小冲 | 来源:发表于2022-01-06 10:55 被阅读0次

    尝试了三种方法:

    1、BinaryReader.ReadBytes

    2、FileStream.Read(bt, 0, Convert.ToInt32(fs.Length));

    3、MemoryStream.GetBuffer();

    图片的宽度200像素,高度是50像素。

    计算字节大小应该为10000

    第一种:

    FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read);

    BinaryReader br = new BinaryReader(fs);

    byte[] bt = new byte[width*height];

    bt = br.ReadBytes(Convert.ToInt32(bt.length));

    结果是  读取 出来的字节数组中少200个字节。不明原因。


    第二种:

    FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read);

    byte[] bt = new byte[width*height];

    fs.Read(bt, 0, Convert.ToInt32(bt.Length));

    结果是  读取 出来的字节数组中少200个字节。不明原因。


    第三种:

    byte[] temp = getImgByte(tempFilePath);  //读取出来是整个图片的字节数据,包括信息头,数据等。

    byte[] bt = new byte[width*height];

    bt = temp.Skip(1078).Take(bt.Length).ToArray();

    经测试发现,信息头固定字节长度为1078个字节。所以从1078开始向后去截取到结尾。就是图片的数据部分。

            public byte[] getImgByte(string FilePath)

            {

                MemoryStream ms = new MemoryStream();

                Image image = Image.FromFile(FilePath);

                try

                {

                    image.Save(ms, ImageFormat.Bmp);

                    byte[] bt = ms.GetBuffer();

                    return bt;

                }

                catch (Exception ex)

                {

                    throw ex;

                }

                finally

                {

                    ms.Close();

                    image.Dispose();

                }

            }


    前两种方法很奇怪,没找到少字节的原因,但发现只要是宽度的尾数不是0就没事,是0就会少字节。第三种方法有点笨,但解决了问题。有需要的人,可以直接拿走使用。

    相关文章

      网友评论

          本文标题:C# 关于 读取图片转字节,发现数组少字节问题

          本文链接:https://www.haomeiwen.com/subject/uzhjcrtx.html