无法将位图转换为byte []

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

所以我正在制作一个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。

c# xamarin xamarin.forms bitmap xamarin.android
1个回答
1
投票

你可以使用byte[]将结果包装成Task.FromResult()而不是返回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;
© www.soinside.com 2019 - 2024. All rights reserved.