2
我有一個網絡REST服務,我試圖從中提取圖像(或wav文件)。 我可以通過內存流獲取圖像(jpg)並將其顯示到圖片框,然後將圖片框保存到文件中。 我想要做的是消除使用圖片框的中間步驟,並將內存流直接保存到文件。但是,生成的文件似乎不是一個jpg文件。 打開時會拋出損壞的文件錯誤。vb.net將網絡二進制文件保存到文件
我的代碼如下:
Dim msgURI As String
msgURI = "http://192.168.0.1/attachment/12345/0"
Dim Pic As New PictureBox()
Dim web_client As New WebClient()
web_client.Credentials = New NetworkCredential("XX", "XX")
Dim image_stream As New MemoryStream(web_client.DownloadData(msgURI))
Pic.Image = Image.FromStream(image_stream)
Dim bm As Bitmap = Pic.Image
Dim filename As String = "c:\temp\test.jpg"
bm.Save(filename, Imaging.ImageFormat.Jpeg)
和工作正常。
然而,當我使用以下方法來繞過位圖和圖片框:
Using file As New FileStream(filename, FileMode.Create, System.IO.FileAccess.Write)
Dim bytes As Byte() = New Byte(image_stream.Length - 1) {}
image_stream.Read(bytes, 0, CInt(image_stream.Length))
file.Write(bytes, 0, bytes.Length)
image_stream.Close()
End Using
我得到一個文件,它是一個已損壞的JPG文件。
任何幫助,非常感謝。
特里