VB.NET 中的 BinaryReader 不工作

BinaryReader in VB.NET don't work

我写了一个代码来保存和显示照片,并在此之前检查它的高度和宽度,但是当我添加代码来识别宽度和高度时,当我使用 "ReadBytes" 方法时它不保存和读取我的数据

Dim fs As Stream = FileUpload1.PostedFile.InputStream

            Dim img As System.Drawing.Image = System.Drawing.Image.FromStream(fs)
            Dim height As Integer = img.Height
            Dim width As Integer = img.Width
            If Not (height < 201 And width < 201) Then
                Me.HsMsg1.MessageType = MessageType.Error
                Me.HsMsg1.Message = " 200*200"
                Me.HsMsg1.Visible = True
                Exit Sub
            End If

            Dim br As New BinaryReader(fs)

            Dim bytes = br.ReadBytes(fs.Length)
            Dim base64String As String = Convert.ToBase64String(bytes, 0, bytes.Length)
            imgDemo.ImageUrl = "data:image/jpeg;base64," & base64String
            imgDemo.Visible = True
            Session("bytes") = bytes

问题出在这一行:

Dim img As System.Drawing.Image = System.Drawing.Image.FromStream(fs)

此行前进到流的末尾。当您稍后创建 BinaryReader 时,您将从流的末尾开始,没有任何内容可读!

我不记得 FileUpload 控件使用的流是否支持搜索(查看 CanSeek 属性 了解),但如果支持,则需要使用 Seek() 方法回到流的开头。如果没有,您将需要 use your img variable as the source to create your byte array... 无论如何这可能是更好的选择。