如何在onActivityResult(){}中获取位图图像

时间:2015-03-13 16:06:40

标签: java android bitmap

我尝试开发一个Android应用程序,从相机捕获图像然后在ImageView上显示它,但它每次都崩溃,在应用程序捕获图像后,.... thankyou

这是我的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);
    }
}

1 个答案:

答案 0 :(得分:0)

我是这样做的:

  1. 创建临时文件以将图像和存储路径存储在成员变量中。
  2. 填写相机意图的EXTRA_OUTPUT参数。
  3. OnActivityResult从您之前存储的路径中读取文件。
  4. 使用代码就像:

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