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

前端 未结 2 1173
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-29 04:36

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

相关标签:
2条回答
  • 2021-01-29 05:06

    This is how I'm getting a Byte[] for my Bitmap object:

    Byte[] imageArray = null;
    Bitmap selectedProfilePic = this.GetProfilePicBitmap ();
    
    if (selectedProfilePic != null) {
        using (var ms = new System.IO.MemoryStream ()) {
            selectedProfilePic.Compress (Bitmap.CompressFormat.Png, 0, ms);
            imageArray = ms.ToArray ();
        }
    }
    

    Hope this helps.

    0 讨论(0)
  • 2021-01-29 05:28

    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.)

    0 讨论(0)
提交回复
热议问题