將字元串轉換為流
我從網上下載了一張圖片並轉換為字元串(這是不可更改的)
Dim Request As System.Net.WebRequest = _ System.Net.WebRequest.Create( _ "http://www.google.com/images/nav_logo.png") Dim WebResponse As System.Net.HttpWebResponse = _ DirectCast(Request.GetResponse(), System.Net.HttpWebResponse) Dim Stream As New System.IO.StreamReader( _ WebResponse.GetResponseStream, System.Text.Encoding.UTF8) Dim Text as String = Stream.ReadToEnd如何將字元串轉換回流?
所以我可以使用該流來獲取圖像。
像這樣:
Dim Image As New Drawing.Bitmap(WebResponse.GetResponseStream)但現在我只有文本字元串,所以我需要這樣的東西:
Dim Stream as Stream = ReadToStream(Text, System.Text.Encoding.UTF8) Dim Image As New Drawing.Bitmap(Stream)編輯:
該引擎主要用於下載網頁,但我也在嘗試使用它來下載圖像。字元串的格式為 UTF8,如範常式式碼中所示…
我嘗試使用
MemoryStream(Encoding.UTF8.GetBytes(Text)),但在將流載入到圖像時出現此錯誤:GDI+ 中出現一般錯誤。
轉換中失去了什麼?
為什麼要將二進制(圖像)數據轉換為字元串?這沒有任何意義……除非您使用的是base-64?
無論如何,要扭轉您所做的事情,您可以嘗試使用
new MemoryStream(Encoding.UTF8.GetBytes(text))?這將創建一個以字元串(通過 UTF8)啟動的新 MemoryStream。就個人而言,我懷疑它會起作用 - 你會遇到很多將原始二進制視為 UTF8 數據的編碼問題……我希望讀取或寫入(或兩者)都會引發異常。
(編輯)
我應該添加它以使用 base-64,只需將數據獲取為 a
byte[],然後呼叫Convert.ToBase64String(...); 並取回數組,只需使用Convert.FromBase64String(...).重新編輯,這正是我在上面試圖警告的內容……在.NET中,字元串不僅僅是 a
byte[],所以你不能簡單地用二進製圖像數據填充它。很多數據對編碼根本沒有意義,因此可能會被悄悄丟棄(或拋出異常)。要將原始二進制(如圖像)作為字元串處理,需要使用 base-64 編碼;然而,這增加了尺寸。請注意,這
WebClient可能會使這更簡單,因為它byte[]直接公開了功能:using(WebClient wc = new WebClient()) { byte[] raw = wc.DownloadData("http://www.google.com/images/nav_logo.png") //... }無論如何,使用標準
Stream方法,以下是對 base-64 進行編碼和解碼的方法:// ENCODE // where "s" is our original stream string base64; // first I need the data as a byte[]; I'll use // MemoryStream, as a convenience; if you already // have the byte[] you can skip this using (MemoryStream ms = new MemoryStream()) { byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = s.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, bytesRead); } base64 = Convert.ToBase64String(ms.GetBuffer(), 0, (int) ms.Length); } // DECODE byte[] raw = Convert.FromBase64String(base64); using (MemoryStream decoded = new MemoryStream(raw)) { // "decoded" now primed with the binary }