how to convert an image into base64 in xamarin.android?

I have this code, it works very well in android studio but not in xamarin bitmap.Compress() has different arguments in xamarin and i am confused how to convert image into base64 or binary in xamarin.android?

I am receving an error in the 3rd line:

( bitmap.Compress() has some invalid arguments).

Bitmap bitmap = BitmapFactory.DecodeResource(Resources, Resource.Drawable.ace1);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100,bao);
byte[] ba = bao.ToByteArray();
string bal = Base64.EncodeToString(ba, Base64.Default);
Jon Skeet
people
quotationmark

If you look at the documentation for Bitmap.Compress in Xamarin, you'll see that the last parameter is a Stream.

The equivalent of ByteArrayOutputStream in .NET is MemoryStream, so your code would be:

Bitmap bitmap = BitmapFactory.DecodeResource(Resources, Resource.Drawable.ace1);
MemoryStream stream = new MemoryStream();
bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, stream);
byte[] ba = stream.ToArray();
string bal = Base64.EncodeToString(ba, Base64.Default);

(You could use Convert.ToBase64String instead of Base64.EncodeToString if you wanted, too.)

people

See more on this question at Stackoverflow