2014-02-05 102 views
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文件。

任何帮助,非常感谢。

特里

回答

0

WebClient.DownloadData方法返回一个字节数组。因此,将字节数组加载到内存流中似乎非常愚蠢,只是为了将其再次读入另一个字节数组中,然后将其保存到文件中。所有这一切都可以很容易地通过直接从第一字节数组将一个文件来完成,像这样:

File.WriteAllBytes("c:\temp\test.jpg", web_client.DownloadData(msgURI)) 

然而,即使是低效率的,因为你可以直接从网络流中的数据文件,如这个:

web_client.DownloadFile(msgURI, "c:\temp\test.jpg")