无法将位图转换为字节[]

时间:2018-09-06 21:09:34

标签: c# xamarin xamarin.forms bitmap xamarin.android

所以我正在制作Xamarin.Forms应用程序。我有一个StackLayout,我要为其快照(仅元素,而不是整个屏幕)。

这是界面:

public interface IViewSnapShot
{
    Task<byte[]> CaptureAsync(Xamarin.Forms.View view);
}

这是事件:

private async Task SavePic_ClickedAsync(object sender, EventArgs e)
    {
        var imageByte = await DependencyService.Get<IViewSnapShot>().CaptureAsync(BlueprintSnapshot);
    }

这是特定于Android平台的:

public class MakeViewSnapshot : IViewSnapShot
{
    Task<byte[]> IViewSnapShot.CaptureAsync(Xamarin.Forms.View view)
    {
        var nativeView = view.GetRenderer().View;
        var wasDrawingCacheEnabled = nativeView.DrawingCacheEnabled;
        nativeView.DrawingCacheEnabled = true;
        nativeView.BuildDrawingCache(false);
        Bitmap bitmap = nativeView.GetDrawingCache(false);
        // TODO: Save bitmap and return filepath
        nativeView.DrawingCacheEnabled = wasDrawingCacheEnabled;

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

        return bitmapData;
    }
}

问题是bitmapData给出了错误

  

无法将类型'byte []'隐式转换为'System.Threading.Tasks.Task'

我有搜索互联网,每篇文章都说这是将位图转换为byte []数组的方法。知道如何解决此错误吗?

稍后,我想将byte []数组上传到Web api。

1 个答案:

答案 0 :(得分:1)

您可以使用Task.FromResult()将结果包装到byte[]中,而不是返回Task

return Task.FromResult(bitmapData);

您的代码可能如下所示:

public class MakeViewSnapshot : IViewSnapShot
{
    Task<byte[]> IViewSnapShot.CaptureAsync(Xamarin.Forms.View view)
    {
        var nativeView = view.GetRenderer().View;
        var wasDrawingCacheEnabled = nativeView.DrawingCacheEnabled;
        nativeView.DrawingCacheEnabled = true;
        nativeView.BuildDrawingCache(false);
        Bitmap bitmap = nativeView.GetDrawingCache(false);
        // TODO: Save bitmap and return filepath
        nativeView.DrawingCacheEnabled = wasDrawingCacheEnabled;

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

        return Task.FromResult(bitmapData);
    }
}

然后稍后要获取byte[]返回的CaptureAsync()时,只需致电:

byte[] result = CaptureAsync(<Your_parameters>).Result;