简体   繁体   中英

Referencing a file on SD-Card, Android

I currently trying to carry out the same operation (OCR) on images in android, one option is to use the camera and the other is to load an image from the SD-CARD. The code works when taken from a camera where the code is

Bitmap bitmap = BitmapFactory.decodeFile(_path,options);

where _path is equal to the last image taken using the application ( _path = DATA_PATH + "ocr.jpg"; ) . However when I try to use an image selected from the gallery where _path would equal,

imageCaptureUri = data.getData();
_path = imageCaptureUri.getPath();

The program locks up with the error

Failure deleiving result ResultInfo{who=null, request = 2, result = -1, data=intent {dat=content://media/external/images/media/26 typ=image/jpeg(has extras)}} to activity{com.project.projectActivity}: java.lang.NullPointerException

If anybody has an idea of whats going on I'd like to hear from you !!

You can get path of the image as..

_path = getPath(imageCaptureUri);


public String getPath(Uri uri) {
String[] projection = { MediaColumns.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
column_index = cursor
    .getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
imagePath = cursor.getString(column_index);

return cursor.getString(column_index);
}

and then

Bitmap bitmap = BitmapFactory.decodeFile(_path,options);

Note : If you are cropping image then this method does not work in this case Gallery will generate cropped image on same directory of image which you are cropping.

The Gallery returns you an Uri to access the image.

You need to use the decodeStream method from BitmapFactory, and for that you need to open an InputStream on the Uri given :

InputStream is = getContentResolver().openInputStream(imageCaptureUri);
Bitmap bitmap = BitmapFactory.decodeStream(is, options);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM