我有一个我试图从中提取图像(或WAV文件)的Web REST服务。我可以通过内存流获取图像(JPG)并将其显示到图片框,然后将图片框保存到文件。我要做的是消除使用图片框的中间步骤,然后直接将内存流保存到文件中。但是,结果文件似乎不是JPG文件。打开时,它会引发损坏的文件错误。
我拥有的代码如下:
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:temptest.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文件的文件。
任何帮助都非常感谢。
Terry
WebClient.DownloadData
方法返回字节数组。因此,将字节数组加载到内存流中似乎很愚蠢,只是将其再次读取到另一个字节数组中,然后将其保存到文件中。所有这些都可以通过直接从第一个字节数组到一个文件来轻松完成,例如:
File.WriteAllBytes("c:temptest.jpg", web_client.DownloadData(msgURI))
但是,即使您可以将数据直接从Web流传输到文件,也是如此效率:
:web_client.DownloadFile(msgURI, "c:temptest.jpg")