如何将图像保存到我的应用程序?

时间:2016-02-22 19:59:24

标签: java android saving-data

我正在创建一个应用程序,让用户可以拍照并将其保存到应用程序中,该应用程序将受密码保护。到目前为止,该应用程序可以拍照,检索它,并将其设置为图像视图。但是,当我重新启动应用程序时,图像消失了。我怎么能保存它?

int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 0;
Uri imageUri;

public void takePic(View view){


    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "filename_" +
            String.valueOf(System.currentTimeMillis()) + ".jpg"));
    intent.putExtra("data", imageUri);
    startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);



}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode == RESULT_OK) {
        if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {


            Bundle extras = data.getExtras();

            Log.e("URI", imageUri.toString());
            Bitmap bmp = (Bitmap) extras.get("data");
            ImageView imageView = (ImageView) findViewById(R.id.imageView);

            imageView.setImageBitmap(bmp);




        }
        else if (resultCode == RESULT_CANCELED) {
            Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT);
        }
    }


}

2 个答案:

答案 0 :(得分:0)

将图像传递给意图 - 图像文件保存在那里。只需将URI保存在SharedPreferences或其他持久存储中,并在下次启动应用时检查该存储。

答案 1 :(得分:0)

这段代码对我有用:

private void takePicture() {

    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    try {
        mImageCaptureUri = null;
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            mImageCaptureUri = Uri.fromFile(mFileTemp);

        }
        else {

            mImageCaptureUri = InternalStorageContentProvider.CONTENT_URI;

        }
        intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, REQUEST_CODE_TAKE_PICTURE);
    } catch (Exception e) {

        Log.d("error", "cannot take picture", e);
    }
}
  

这是如何定义mFileTemp

String state = Environment.getExternalStorageState();
File mFileTemp;
if (Environment.MEDIA_MOUNTED.equals(state)) {
//this is like that 
//any folder name/you can add inner folders like that/your photo    name122412414124.jpg
mFileTemp = new File(Environment.getExternalStorageDirectory()+File.separator+"any folder name"+File.separator+"you can add inner folders like that"
        , "your photo name"+System.currentTimeMillis()+".jpg");
mFileTemp.getParentFile().mkdirs();
}
else {
mFileTemp = new File(getFilesDir()+"any folder name"+
        File.separator+"myphotos")+File.separator+"profilephotos", "your photo name"+System.currentTimeMillis()+".jpg");
mFileTemp.getParentFile().mkdirs();
}
  

您的全局变量

private Uri mImageCaptureUri;
private File mFileTemp;

1)定义全局变量

2)然后定义mFileTemp

3)然后触发takePicture()方法