Android: How to load image into Bitmap

2019-04-02 09:26发布

问题:

I am able to load a resource image, from drawable folder, into a bitmap and even scale fine, however now I have a need to load an image from any stored on the SD-Card and I can see this will allow me to view and select;

    startActivityForResult(new Intent(Intent.ACTION_PICK,
         android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI), 1);

However so far I have been unable to find out exactly what data is returned and how to load it into a bitmap.

UPDATED:

This is now what I got;

@Override
protected void onActivityResult(int requestCode, int resultCode,
            Intent intent) {
  super.onActivityResult(requestCode, resultCode, intent);

if (resultCode == RESULT_OK) {

    Uri contentURI =  Uri.parse(intent.getDataString());

    c = mSurfaceHolder.lockCanvas();

    tempCanvas.setBitmap(mDrawing);

    Bitmap tempBitmap = null;

    ContentResolver cr = getContentResolver();

    try {           
      InputStream in = cr.openInputStream(contentURI);
      BitmapFactory.Options options = new BitmapFactory.Options();
      options.inSampleSize=8;
      tempBitmap = BitmapFactory.decodeStream(in,null,options);
        }
    catch (Exception ee) {
      tempBitmap = BitmapFactory.decodeResource(getResources(),
                    R.drawable.icon);
        }

    tempCanvas.drawBitmap(tempBitmap, 0, 0, null);
    c.drawBitmap(tempBitmap, 0, 0, null);

    mSurfaceHolder.unlockCanvasAndPost(c);
  }
}

And it errors out with "app has stopped unexpectedly" with logcat showing;

ERROR/AndroidRuntime(24768): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { act=com.htc.HTCAlbum.action.ITEM_PICKER_FROM_COLLECTIONS dat=content://media/external/images/media/185 }} to activity {com.example.colorbook/com.example.colorbook.Colorbook}: java.lang.NullPointerException


Complete logcat as it finished gallery view activity and tried to return intent;<br>
02-03 10:47:22.042: DEBUG/MainActivity(22984): [HTCAlbum][MainActivity][onPause]: Begin<br>02-03 10:47:22.042: DEBUG/MainActivity(22984): store mCurrentPosition_backup=0<br>02-03 10:47:22.042: DEBUG/DisplayManager(22984): store mCurrentPosition_backup=0<br>02-03 10:47:22.092: DEBUG/dalvikvm(22984): GC_EXPLICIT freed 1459 objects / 91880 bytes in 44ms<br>02-03 10:47:22.102: INFO/AlbumMapper(22984): Create thumbnail for: /mnt/sdcard/workspace/Colorbook/res/drawable/fileload.png<br>02-03 10:47:22.102: DEBUG/ThumbnailWorker(22984): [stopWorking] Stop working, now join #37, /mnt/sdcard/workspace/Colorbook/res/drawable/fileload.png<br>02-03 10:47:22.102: DEBUG/AlbumAdapter(22984): set thread priority to normal<br>02-03 10:47:22.102: DEBUG/AbstractViewGetter(22984): Raise getter prefetcher thread priority to normal.<br>02-03 10:47:22.102: DEBUG/AbstractViewGetter(22984): Join getter prefetch thread<br>02-03 10:47:22.102: DEBUG/AbstractViewGetter(22984): Getter prefetch join time: 2<br>02-03 10:47:22.102: DEBUG/AlbumMapper(22984): cancel current decode operation<br>02-03 10:47:22.182: DEBUG/AndroidRuntime(24768): Shutting down VM<br>02-03 10:47:22.182: WARN/dalvikvm(24768): threadid=1: thread exiting with uncaught exception (group=0x400259f8)<br>02-03 10:47:22.182: ERROR/AndroidRuntime(24768): FATAL EXCEPTION: main<br>02-03 10:47:22.182: ERROR/AndroidRuntime(24768): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { act=com.htc.HTCAlbum.action.ITEM_PICKER_FROM_COLLECTIONS dat=content://media/external/images/media/185 }} to activity {com.example.colorbook/com.example.colorbook.Colorbook}: java.lang.NullPointerException<br>02-03 10:47:22.182: ERROR/AndroidRuntime(24768):     at android.app.ActivityThread.deliverResults(ActivityThread.java:3734)<br>02-03 10:47:22.182: ERROR/AndroidRuntime(24768):     at android.app.ActivityThread.handleSendResult(ActivityThread.java:3776)<br>02-03 10:47:22.182: ERROR/AndroidRuntime(24768):     at android.app.ActivityThread.access$2800(ActivityThread.java:135)<br>02-03 10:47:22.182: ERROR/AndroidRuntime(24768):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2166)<br>02-03 10:47:22.182: ERROR/AndroidRuntime(24768):     at android.os.Handler.dispatchMessage(Handler.java:99)<br>02-03 10:47:22.182: ERROR/AndroidRuntime(24768):     at android.os.Looper.loop(Looper.java:144)<br>02-03 10:47:22.182: ERROR/AndroidRuntime(24768):     at android.app.ActivityThread.main(ActivityThread.java:4937)<br>02-03 10:47:22.182: ERROR/AndroidRuntime(24768):     at java.lang.reflect.Method.invokeNative(Native Method)<br>02-03 10:47:22.182: ERROR/AndroidRuntime(24768):     at java.lang.reflect.Method.invoke(Method.java:521)<br>02-03 10:47:22.182: ERROR/AndroidRuntime(24768):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)<br>02-03 10:47:22.182: ERROR/AndroidRuntime(24768):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)<br>02-03 10:47:22.182: ERROR/AndroidRuntime(24768):     at dalvik.system.NativeStart.main(Native Method)<br>02-03 10:47:22.182: ERROR/AndroidRuntime(24768): Caused by: java.lang.NullPointerException<br>02-03 10:47:22.182: ERROR/AndroidRuntime(24768):     at com.example.colorbook.Colorbook.loadImageToCanvas(Colorbook.java:524)<br>02-03 10:47:22.182: ERROR/AndroidRuntime(24768):     at com.example.colorbook.Colorbook.onActivityResult(Colorbook.java:231)<br>02-03 10:47:22.182: ERROR/AndroidRuntime(24768):     at android.app.Activity.dispatchActivityResult(Activity.java:3931)<br>02-03 10:47:22.182: ERROR/AndroidRuntime(24768):     at android.app.ActivityThread.deliverResults(ActivityThread.java:3730)<br>02-03 10:47:22.182: ERROR/AndroidRuntime(24768):     ... 11 more<br>02-03 10:47:22.202: WARN/ActivityManager(97):   Force finishing activity com.example.colorbook/.Colorbook<br>02-03 10:47:22.704: WARN/ActivityManager(97): Activity pause timeout for HistoryRecord{46207010 com.example.colorbook/.Colorbook}<br>02-03 10:47:22.742: DEBUG/Sensors(97): close_akm, fd=114<br>02-03 10:47:22.852: DEBUG/MainActivity(22984): [HTCAlbum][MainActivity][onStop]: Begin<br>02-03 10:47:22.902: DEBUG/dalvikvm(22984): GC_EXPLICIT freed 398 objects / 23264 bytes in 38ms<br>02-03 10:47:22.902: DEBUG/MainActivity(22984): [HTCAlbum][MainActivity][onDestroy]: Begin<br>02-03 10:47:22.912: DEBUG/OnlineDataCenter(22984): [HTCAlbum][OnlineDataCenter][unbindContext]: Begin<br>02-03 10:47:22.912: DEBUG/OnlineDataCenter(22984): [HTCAlbum][OnlineDataCenter][unbindContext]: com.htc.album.MainActivity@46075ec0context size: 0<br>02-03 10:47:22.912: DEBUG/OnlineDataCenter(22984): [HTCAlbum][OnlineDataCenter][unbindContext]: No more clients. release resources.<br>02-03 10:47:22.912: DEBUG/OnlineDataCenter(22984): [HTCAlbum][OnlineDataCenter][unbindContext]: End 0<br>02-03 10:47:22.912: DEBUG/ThumbnailWorker(22984): [stopWorking] Stop working, now join #-1, Decode Complete!!<br>02-03 10:47:22.912: DEBUG/AlbumAdapter(22984): set thread priority to normal<br>02-03 10:47:22.912: DEBUG/AlbumMapper(22984): cancel current decode operation<br>02-03 10:47:22.912: DEBUG/AlbumMapper(22984): cancel current decode operation<br>02-03 10:47:22.912: DEBUG/ThumbnailWorker(22984): [stopWorking] Stop working, now join #-1, Decode Complete!!<br>02-03 10:47:22.912: DEBUG/AlbumAdapter(22984): set thread priority to normal<br>02-03 10:47:22.912: DEBUG/AlbumAdapter(22984): Join worker thread in destroy<br>02-03 10:47:22.912: DEBUG/AlbumAdapter(22984): Join time: 0<br>02-03 10:47:22.922: INFO/MainActivity(22984): mWorker finishes jobs at onDestroy().<br>02-03 10:47:22.932: DEBUG/CollectionsActivity(22984): [HTCAlbum][CollectionsActivity][onDestroy]: Begin<br>02-03 10:47:22.932: DEBUG/AlbColAdap(22984): [HTCAlbum][AlbumCollectionsAdapter][onDestroy]: Begin<br>02-03 10:47:22.942: INFO/BatteryStatsImpl(97): notePhoneSignalStrengthLocked: 2->3<br>02-03 10:47:22.952: DEBUG/AlbColAdap(22984): [HTCAlbum][AlbumCollectionsAdapter][onDestroy]: End<br>

回答1:

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



回答2:

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.



回答3:

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