保存图片并在imageview中打开

时间:2014-03-01 18:56:02

标签: android image view

当我拍照时,图片将保存在硬盘上,然后在imageview中打开图片。

在我的命令中,图片将被保存,但应用程序崩溃了。

public class Note  extends Activity {

TextView t;
ImageView iv;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.note);
   iv=(ImageView) findViewById(R.id.imageView);

    Button btn = (Button) findViewById(R.id.photo);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent, 0);
        }
    });


}
public void button (View view){
    Intent intent = new Intent(view.getContext(),Note2.class);
    startActivityForResult(intent, 0);
}



@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(requestCode==0)
    {
    Bitmap theImage = (Bitmap) data.getExtras().get("data");
        iv.setImageBitmap(theImage);

    }}
}

如何重写命令才能使其正常工作?

 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode==0)
        {
        Bitmap theImage = (Bitmap) data.getExtras().get("data");
            iv.setImageBitmap(theImage);

1 个答案:

答案 0 :(得分:0)

首先,请确保您的Manifest拥有此权限:

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

其次,您的onActivityResult方法应该是这样的,声明File并将Bitmap存储到设备中,如下所示:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch(requestCode){
  case 0:
    final File file = getTempFile(this);
    try {
      Bitmap captureBmp = Media.getBitmap(getContentResolver(), Uri.fromFile(file) );
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  break;
  }
}
}

这是关于捕捉图像的非常好的example