我已经为这个实现苦苦挣扎了几个小时,无论我在哪里(SO、Xamarin 论坛、谷歌等)似乎都找不到任何解决方案......
在当前的场景中,我有一些图像,我希望从我的共享代码.Droid.Resources.Drawable
中访问这些图像并将其转换为图像。byte[]
这是因为我希望在我设置为服务器端点的 REST API 上测试我的CRUD功能的全部范围。
这些图像在应用程序中显示得很好,但由于某种原因,我似乎根本无法在将这些图像转换为byte[]
Xamarin 中的过程中扭曲我的头脑。我在“普通” C#中做过无数次......
对不起,如果代码有点乱,但我相信你明白了。
- 我想从存储中获取图像
.Droid
(稍后将移植到 iOS) - 将所述图像转换为
byte[]
- 将该表示发送
byte[]
到我的 API。
在代码的当前状态下,我收到此错误:
C#:无法创建抽象类的实例
我试图在哪里创建一个新的 Stream ( new Stream(sauce)
)
下面的示例基于此处找到的片段,并且完全归功于 Sten 和 Vincent。
/*
* 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();
}
}