0

我已经为这个实现苦苦挣扎了几个小时,无论我在哪里(SO、Xamarin 论坛、谷歌等)似乎都找不到任何解决方案......

在当前的场景中,我有一些图像,我希望从我的共享代码.Droid.Resources.Drawable中访问这些图像并将其转换为图像。byte[]这是因为我希望在我设置为服务器端点的 REST API 上测试我的CRUD功能的全部范围。

这些图像在应用程序中显示得很好,但由于某种原因,我似乎根本无法在将这些图像转换为byte[]Xamarin 中的过程中扭曲我的头脑。我在“普通” C#中做过无数次......

对不起,如果代码有点乱,但我相信你明白了。

  1. 我想从存储中获取图像.Droid(稍后将移植到 iOS)
  2. 将所述图像转换为byte[]
  3. 将该表示发送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();
        }
    }
4

1 回答 1

1

尝试使用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();
        }
    }

希望这可以帮助!

于 2017-04-12T19:34:35.043 回答