1
votes
UserAvatar = FindViewById<ImageView>(Resource.Id.profilePic);  
BitmapDrawable drawable = (BitmapDrawable)UserAvatar.GetDrawableState();
Bitmap bitmap = drawable.Bitmap;
MemoryStream baos = new MemoryStream();
bitmap.Compress(Bitmap.CompressFormat.Png, 100, baos);
byte[] bb = baos.ToArray();
String image = Base64.Encode(bb, Base64Flags.Default).ToString();

I am trying to encode imageview image to base64 string format but i am getting cast exception in

BitmapDrawable drawable = (BitmapDrawable)UserAvatar.GetDrawableState();

into this aboue line please me.I am implemeting this code in c# Xamarin

2

2 Answers

0
votes

This happens because, actually, GetDrawableState() returns an int[] and represents ID's of states. To get drawable from ImageView you should use GetDrawable() as shown here https://forums.xamarin.com/discussion/14939/is-there-a-way-to-get-bitmap-from-imageview

0
votes

As already noted GetDrawableState() returns a int32[] value.


Refer the below code in Image to Base64 Conversion. It will help you sometimes.

Base64 to Bitmap :

public Bitmap Base64ToBitmap(String base64String)
{
    byte[] imageAsBytes = Base64.Decode(base64String, Base64Flags.Default);
    return BitmapFactory.DecodeByteArray(imageAsBytes, 0, imageAsBytes.Length);
}

Bitmap to Base64 :

public String BitmapToBase64(Bitmap bitmap)
{
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    bitmap.Compress(Bitmap.CompressFormat.Png, 100, byteArrayOutputStream);
    byte[] byteArray = byteArrayOutputStream.ToByteArray();
    return Base64.EncodeToString(byteArray, Base64Flags.Default);
}