Android: How to load image into Bitmap

允我心安 提交于 2019-12-03 21:36:36

I use this intent:

myIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

And later on use this to get the image

protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { 
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
    switch(requestCode){
    case IMAGE_UPLOAD: //this is a constant, in your case I think it should be '1'
        if(imageReturnedIntent != null){// e.g. "back" pressed"
            Uri contentURI = Uri.parse(imageReturnedIntent.getDataString());        
            ContentResolver cr = getContentResolver();
            InputStream in = cr.openInputStream(contentURI);
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize=8;
            Bitmap thumb = BitmapFactory.decodeStream(in,null,options);
       }
    break;

}

I'm sending that string around a bit, but in the end this is what happens:

there you are with , in this case, a thumb of the image. If you want it bigger, use a different samplesize :)

The data that is returned is the Uri of the image that was selected, you will still need to load the image. In your onActivityResult:

public void onActivityResult(int reqCode, int resultCode, Intent data) {
     ...some code to make sure the result is valid
     Uri imageUri = data.getData();
     imageView.setImageUri(imageUri);
}

And also you will have to use EXTERNAL_CONTENT_URI vs INTERNAL_CONTENT_URI. This also loads the image on the UI thread which you probably won't want to do. You'll want to pass it off to a background thread.

Try this :

private String getPath(Uri uri) {
String[]  data = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(context, uri, data, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!