1

When I am calling this function there is no image/string in _bitmap. In my application, I select image from the gallery and convert it to base64. I had debugged the app for the problem, so I found that the method BitmapFactory.decodeFile("image path") is returning null value even though the path which I am getting is totally fine.

 private void _btnResimYolu_Click(object sender, System.EventArgs e)
 {
     var imageIntent = new Intent();
     imageIntent.SetType("image/*");

     imageIntent.SetAction(Intent.ActionGetContent);
     StartActivityForResult(Intent.CreateChooser(imageIntent, "Select Image"), 0);
 } 

 protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
 {
     base.OnActivityResult(requestCode, resultCode, data);

     if (resultCode == Result.Ok)
     {
         var imageView = FindViewById<ImageView>(Resource.Id.img1);
         imageView.SetImageURI(data.Data);
         _imageTest.Text = data.DataString;                   
     }   
 }

 private void _gonder_Click(object sender, System.EventArgs e)
 {           
     string uriString = _imageTest.Text;
     _bitmap = BitmapFactory.DecodeFile(uriString);
     MemoryStream stream = new MemoryStream();
     _bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, stream);
     byte[] ba = stream.ToArray();
     string bal = Base64.EncodeToString(ba, Base64.Default);
 }
Nick Peppers
  • 3,161
  • 23
  • 27

1 Answers1

1

BitmapFactory.decodeFile() returning null

The problem is that your get the wrong image path, so the BitmapFactory.DecodeFile(uriString) always return null. The data.DataString in OnActivityResult is my device is :

[0:] data.Data = content://com.miui.gallery.open/raw/%2Fstorage%2Femulated%2F0%2FDCIM%2FCamera%2FIMG_20171125_143057.jpg

Solution :

When you choose a picture, you should convert its Uri to a real path. You could refer to my answer : How to get actual path from Uri xamarin android. Then, modify your code like this :

protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
    base.OnActivityResult(requestCode, resultCode, data);
    if (requestCode == Result.Ok)
    {
        var uri = data.Data;

        //You could find the GetActualPathFromFile() method code in the above link I have post.
        string path = GetActualPathFromFile(uri);

        _imageTest.Text = path ; 

        System.Diagnostics.Debug.WriteLine("data.Data = " + data.Data);
        System.Diagnostics.Debug.WriteLine("path = " + path);
    }
}

The image path :

[0:] path = /storage/emulated/0/DCIM/Camera/IMG_20171125_143057.jpg

Then you could BitmapFactory.DecodeFile() to implement your function.

Update :

Please make sure you have the WRITE_EXTERNAL_STORAGE permission, since Android 6.0, you have to Requesting Permissions at Run Time.

York Shen
  • 9,014
  • 1
  • 16
  • 40