将Xamarin位图转换为字节[]不起作用或引发异常

问题描述 投票:0回答:1

我试图将摄像机的图像转换为字节[],然后向服务器发出请求,但该服务器无法正常工作,因此摄像机的图像为

var image = textureView.Bitmap;
image = Android.Graphics.Bitmap.CreateBitmap
    (image,
    (int)OCR_Rectangle.GetX(),
    (int)OCR_Rectangle.GetY(),
    OCR_Rectangle.Width,
    OCR_Rectangle.Height);

我的网络请求是

public async static Task<string> ParseAsync(byte[] image)
{
    string id = "my id ";
    string apiKey = "my api key ";
    using (var httpClient = new HttpClient())
    {
        httpClient.DefaultRequestHeaders.TryAddWithoutValidation("app_id", id);
        httpClient.DefaultRequestHeaders.TryAddWithoutValidation("app_key", apiKey);
        var base64 = Convert.ToBase64String(image);
        var imageUri = "data:image/jpg;base64," + base64;
        var json = JsonConvert.SerializeObject(new { src = imageUri });
        var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
        var response = await httpClient.PostAsync("my website", content);
        var dynObj = JsonConvert.DeserializeObject<RootObjectLatex>(await response.Content.ReadAsStringAsync());
        return dynObj.latex;
    }
}

这是我尝试将位图转换为字节[]

byte[] bitmapData;
using (var stream = new MemoryStream())
{
    image.Compress(Bitmap.CompressFormat.Png, 0, stream);
    bitmapData = stream.ToArray();
}

然后我想在请求中使用bitmapData。但不走运。

c# xamarin.android
1个回答
0
投票

可能需要在开始时“重新定位”流。试试这个:

byte[] bitmapData;
using (var stream = new MemoryStream())
{
    image.Compress(Bitmap.CompressFormat.Png, 0, stream);
    stream.Position = 0;

    using (var streamReader = new StreamReader(stream))
    {
        return streamReader.ToArray();
    }
}

((尚未测试,对不起)

© www.soinside.com 2019 - 2024. All rights reserved.