简体   繁体   中英

Cannot convert bitmap to byte[]

So I'm making a Xamarin.Forms app. I have a StackLayout, of which I'm taking a snapshot(only the element, not the whole screen.)

This is the interface:

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

this is the event:

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

and this is Android platform specific:

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;
    }
}

The problem is bitmapData gives error

Cannot implicitly convert type 'byte[]' to 'System.Threading.Tasks.Task'

I have search internet, and every post says that this is the way to convert bitmap to byte[] array. Any idea how to fix this error?

Later I'll want to upload the byte[] array to web api.

Instead of returning a byte[] , you can use the Task.FromResult() to wrap a result into a Task :

return Task.FromResult(bitmapData);

Your code might looks like this:

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);
    }
}

And then later when you want to get the byte[] returned by CaptureAsync() you just need to call:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM