【问题标题】:MemoryStream.Read doesn't copy bytes to buffer - c#MemoryStream.Read 不会将字节复制到缓冲区 - c#
【发布时间】:2010-09-27 10:20:03
【问题描述】:

我真的不明白,这让我发疯。 我有这 4 行:

Image img = Image.FromFile("F:\\Pulpit\\soa.bmp");
MemoryStream imageStream = new MemoryStream();
img.Save(imageStream, ImageFormat.Bmp);
byte[] contentBuffer = new byte[imageStream.Length];
imageStream.Read(contentBuffer, 0, contentBuffer.Length);

调试时我可以看到 imageStream 中的字节值。在 imageStream.Read 之后我检查 contentBuffer 的内容,我只看到 255 个值。 我不明白为什么会这样?这几行没有什么可做的! 如果有人可以帮助我,将不胜感激! 谢谢, 阿格涅斯卡

【问题讨论】:

    标签: c# image buffer memorystream


    【解决方案1】:

    随便用

    imageStream.ToArray()
    

    它工作起来更容易。

    【讨论】:

    • ToArray() 每次都会创建一个新的 byte[] ,从而产生垃圾,有时这样就不行了
    【解决方案2】:
    Image img = Image.FromFile("F:\\Pulpit\\soa.bmp");
    MemoryStream imageStream = new MemoryStream();
    img.Save(imageStream, ImageFormat.Bmp);
    byte[] contentBuffer = new byte[imageStream.Length];
    imageStream.Position = 0;//Reset the position at the start
    imageStream.Read(contentBuffer, 0, contentBuffer.Length);
    

    【讨论】:

      【解决方案3】:

      添加:

      imageStream.Position = 0;
      

      就在之前:

      imageStream.Read(contentBuffer, 0, contentBuffer.Length);
      

      读取指令中的 0 代表内存流中当前位置的偏移量,而不是流的开始。加载流后,位置位于末尾。您需要将其重置为开头。

      【讨论】:

        【解决方案4】:

        尝试将 imageStream.Position 设置为 0。当您写入 MemoryStream 时,它会将 Position 移动到您刚刚写入的字节之后,因此如果您尝试读取,那里什么都没有。

        【讨论】:

          【解决方案5】:

          您需要重置文件指针。

          imageStream.Seek( 0, SeekOrigin.Begin );
          

          否则,您将从流的末尾读取。

          【讨论】:

            猜你喜欢
            • 2012-07-17
            • 1970-01-01
            • 1970-01-01
            • 2015-10-29
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多