Bharathi
Bharathi

Reputation: 1328

Convert ByteArray into png image and add it to ImageView in Xamarin.Android

I have the Image ByteArray and want to convert the byte array into png image and add in ImageView as you see in the below code.

 byte[] imageBytes =  webClient.DownloadDataTaskAsync(uri);


 ImageView view = new ImageView(this.Context);

  //Here need to add the converted image into ImageView
  view.SetImageSource();

I achieved this, by converting ImageBytes into a bitmap and add the bitmap in ImageView. But it has some memory problem. As I adding more no.of times frequently in my source, I couldn't use a bitmap to add in ImageView due to the memory exception.

So please help me.

Thanks.

Upvotes: 2

Views: 1871

Answers (2)

Toni Kostelac
Toni Kostelac

Reputation: 361

You can do it by creating the bitmap from Stream to do that use this:

using(var ms = new MemoryStream(imageBytes))
{
    var bitmap = BitmapFactory.DecodeStream(ms);
    // ...
    // rest of your logic here...
    // ...
}

Hope this helps

Upvotes: 2

TheGeneral
TheGeneral

Reputation: 81493

It should be as easy as calling

var bitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);

Android.Graphics.BitmapFactory.DecodeByteArray Method

Decode an immutable bitmap from the specified byte array.

Parameters

  • data
    • byte array of compressed image data
  • offset
    • offset into imageData for where the decoder should begin parsing.
  • length
    • the number of bytes, beginning at offset, to parse
  • opts
    • null-ok; Options that control downsampling and whether the image should be completely decoded, or just is size returned.

Upvotes: 2

Related Questions