2017-04-12 74 views
0

我一直在爲這個實現掙扎幾個小時,似乎無法在任何地方找到任何解決方案(所以,Xamarin論壇,Google等)。 ..無法從字節[]轉換的存儲圖像創建流

在這種情況下,我有一些.Droid.Resources.Drawable的圖像,我希望從我的共享代碼中訪問並轉換爲byte[]。這是由於我希望在我設置爲服務器端點的REST API上測試我的CRUD功能的全部範圍。

圖像在應用程序中顯示出來很好,但由於某種原因,我似乎無法扭轉我的頭在Xamarin中將這些圖像轉換爲byte[]的過程。我在'正常'中做了無數次C# ...

對不起,如果代碼有點混亂,但我相信你明白了。

  1. 我想從.Droid存儲獲得的圖像(將被移植於iOS版本)
  2. 轉換所述圖像成byte[]
  3. 發送該byte[]表示我的API。

在代碼的當前狀態,我得到這個錯誤:

C#: An instance of an abstract class can not be created

當我試圖創建一個新流(new Stream(sauce)


下面的例子是基於在片段發現here和充分的信貸去Sten和文森特。

/* 
    * Takes an arbitrary string as a token, updates a record with dummy data and a placeholder_image. 
    */ 
    public async Task<string> PostUpdateFoundation(string arbitrary, Image img) 
    { 

     ImageSource sauce = ImageSource.FromFile("abc.png"); 
     byte[] byte_img = FromStreamToByte(new Stream(sauce)); //error occurs here 
     Debug.WriteLine("I'm in!"); 
     var client = new System.Net.Http.HttpClient(); 
     client.DefaultRequestHeaders.Add("Accept", "application/json"); 

     var content = new StringContent(arbitrary); 
     var response = await client.PostAsync(String.Format("http://some.api.to.test.com?s={0}&img={1}", arbitrary, byte_img), content); 
     var result = response.Content.ReadAsStringAsync().Result; 
     return result; 

    } 
    /* 
    * Attempts to convert an stream (based on image source) into a byte[]. 
    */ 
    public static byte[] FromStreamToByte (Stream input) 
    { 
     using (MemoryStream ms = new MemoryStream()) 
     { 
      input.CopyTo(ms); 
      return ms.ToArray(); 
     } 
    } 
+0

根據你的錯誤是什麼或在哪裏? –

+0

對不起,遺憾的是。所有這一切都讓這個該死的混淆了。 在代碼的當前狀態下,我正在嘗試創建「新Stream(醬)」的行上出現「C#:無法創建抽象類的實例」錯誤。 – geostocker

+0

你爲什麼試圖包含一個字節數組作爲查詢字符串參數?你期望做什麼?你有效地在'byte []'上調用'ToString()',它真的不會成爲你想要的。我懷疑你希望你的圖像數據在請求的主體中,或者作爲二進制數據,或者(如果你還需要文本)作爲base64。 –

回答

0

嘗試使用Plugin.Media

  byte BImageSource = ReadFully(file.GetStream()); 
      var bytes = new byte[file.GetStream().Length]; //file is from the plugin and contains your image 
      file.GetStream().Position = 0; 
      file.GetStream().Read(bytes, 0, (int)file.GetStream().Length); 
      BImageSource = ReadFully(file.GetStream()); //BImageSource is your resource in bytes 

    byte[] ReadFully(Stream input) 
    { 
     using (MemoryStream ms = new MemoryStream()) 
     { 
      input.CopyTo(ms); 
      return ms.ToArray(); 
     } 
    } 

希望這有助於!