BitmapFactory.decodeFile()返回null xamarin.android

时间:2017-12-08 14:36:16

标签: xamarin.android

当我调用此函数时,_bitmap中没有图像/字符串。在我的应用程序中,我从库中选择图像并将其转换为base64。我已经调试了应用程序的问题,所以我发现方法BitmapFactory.decodeFile("image path")正在返回null值,即使我得到的路径完全正常。

 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);
 }

1 个答案:

答案 0 :(得分:1)

  

BitmapFactory.decodeFile()返回null

问题是您获取了错误的图像路径,因此BitmapFactory.DecodeFile(uriString)始终返回null。 data.DataString中的OnActivityResult是我的设备:

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

解决方案:

选择图片时,应将其Uri转换为真实路径。你可以参考我的回答:How to get actual path from Uri xamarin android。然后,修改你的代码:

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);
    }
}

图片路径:

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

然后你可以BitmapFactory.DecodeFile()来实现你的功能。

更新:

请确保您拥有WRITE_EXTERNAL_STORAGE权限,自Android 6.0起,您必须Requesting Permissions at Run Time