mabel
mabel

Reputation: 177

SKBitmap.Decode(imageStream) is returning null

I am trying to use skiasharp to edit an image I have as a stream, but when I try to turn it into an SKBitmap the resulting variable is always none. I am using Xam.Plugin.Media to get the image.

var photo = await Plugin.Media.CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions() { SaveToAlbum = false });

if (photo != null)
{
    var imageStream = photo.GetStream();
    SKBitmap bitmap = SKBitmap.Decode(imageStream);
    using (SKPaint textPaint = new SKPaint { TextSize = 48 })
    using (SKCanvas canvas = new SKCanvas(bitmap))
    {
        canvas.DrawText("test", 0, 0, textPaint);
    }

    SKImage image = SKImage.FromBitmap(bitmap);
    SKData encoded = image.Encode();
    Stream stream = encoded.AsStream();

    PhotoImage.Source = ImageSource.FromStream(() => { return stream; });
}

Upvotes: 3

Views: 2202

Answers (2)

Phillip
Phillip

Reputation: 175

I just ran into this issue myself and was able to work around it by loading the stream into a byte array first.

var fs = new FileStream("Path", FileMode.Open);
var imageStream = new MemoryStream();
fs.CopyTo(imageStream);

var imageBytes = imageStream.ToArray();
var bitmap = SkiaSharp.SKBitmap.Decode(imageBytes);

Upvotes: 1

Shawn Pan
Shawn Pan

Reputation: 101

I add this line after obtaining a stream with var imageStream = photo.GetStream();

imageStream.seek(0, SeekOrigin.Begin);

Upvotes: 2

Related Questions