简体   繁体   中英

How to get bitmap image inside onActivityResult( ){ }

i try to develope an android app that capture image from camera then show it on ImageView, but it crash every time, after the app capture the image,....thankyou

here is my javacode

 public class MainActivity extends ActionBarActivity {
 private ImageView mImageView;
    static final int REQUEST_IMAGE_CAPTURE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mImageView=(ImageView)findViewById(R.id.image);

      }
    public void klik(View view){
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            Bundle extras = data.getExtras();
            Bitmap imageBitmap = (Bitmap) extras.get("data");
            mImageView.setImageBitmap(imageBitmap);
        }
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

I did it this way:

  1. Create a temp file to store the image and store path in a member variable.
  2. Fill the EXTRA_OUTPUT parameter for the camera intent.
  3. OnActivityResult read the file from the path you stored before.

With code it's something like:

// 1.
File tempFile = File.createTempFile("camera", ".png", getExternalCacheDir());
mPath = tempFile.getAbsolutePath();
Uri uri = Uri.fromFile(tempFile);

// 2.
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);

// 3.
protected void onActivityResult(int requestCode, int resultCode, Intent data){
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
    Bitmap bitmap = BitmapFactory.decodeFile(mPath, options);

    mImageView.setImageBitmap(bitmap);
}

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