DeadlyChambers
DeadlyChambers

Reputation: 5284

How to change a Android.graphics.bitmap into a byte array in c#

I have an android.graphics.bitmap and an android.net.Uri both of these I can use anyway I want. But I don't know how to take the bitmap and turn it into a byte[] I have tried using a Parcel but I can't initialize it, and when I use it in the writetoparcel method for both the bitmap and uri it throws an error.

I tried the bitmaps ToArray method and that does nothing but create an empty array. I also tried to use the compress method but I cannot initialize a stream. The text editor throws an error about creating a new Stream inside an abstract class.

Is there some reference that I am missing that allows me to do this.

Upvotes: 0

Views: 6431

Answers (3)

Nurhak Kaya
Nurhak Kaya

Reputation: 1781

This is how you do it.

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

Upvotes: 3

DeadlyChambers
DeadlyChambers

Reputation: 5284

This is what I ended up using to get it into a byte array and resize.

Bitmap thumb;
Android.Net.Uri val;
this.thumb = MediaStore.Images.Media.GetBitmap(this.ContentResolver, this.val);                        
Bitmap scaledThumb = Bitmap.CreateScaledBitmap(this.thumb, 1600, 1200, true);                        
MemoryStream stream = new MemoryStream();
scaledThumb.Compress(Bitmap.CompressFormat.Jpeg, 50, stream);
this.byteArr = stream.ToArray();

Upvotes: 3

jpobst
jpobst

Reputation: 9982

My guess is you would want to use:

Android.Graphics.Bitmap.CopyPixelsToBuffer (Java.Nio.Buffer)

or:

Android.Graphics.Bitmap.GetPixels (int[], int, int, int, int, int, int)

Upvotes: 1

Related Questions