【问题标题】:Trying to take a picture and then store it + have access to it尝试拍照然后存储它+可以访问它
【发布时间】:2016-04-04 08:31:37
【问题描述】:

所以,我有一个应用程序,我想在其中拍照,将其存储到内部存储中,然后能够稍后检索它(可能是通过它的 Uri)。到目前为止,这是我所拥有的: 按下我的自定义相机按钮时会触发此代码。

cameraButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final Intent takePic = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            File file = herp(MEDIA_TYPE_IMAGE);
            if (file != null) {
                fileUri = getOutputMediaFileUri(file);
                Log.d("AddRecipeActivity", fileUri.toString());
                takePic.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
                startActivityForResult(takePic, CAMERA_REQUEST);
            }
        }
    });

接下来,我稍后在代码中定义了两个方法(主要取自 android 开发者网站):

 /** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(File file){
    return Uri.fromFile(file);
}

/** Create a File for saving an image or video */
public File herp(int type){
    // To be safe, you should check that the SDCard is mounted
    // using Environment.getExternalStorageState() before doing this.
    Boolean a = false;
    String externalDirectory= getFilesDir().getAbsolutePath();
    File folder= new File(externalDirectory + "/NewFolder");


    // This location works best if you want the created images to be shared
    // between applications and persist after your app has been uninstalled.

    // Create the storage directory if it does not exist


    if (!folder.exists()){
        a = folder.mkdirs();
        Log.d("AddRecipeActivity", String.valueOf(a));
        }




    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    File mediaFile;
    if (type == MEDIA_TYPE_IMAGE){
        mediaFile = new File(folder.getPath() + File.separator +
                "IMG_"+ timeStamp + ".jpg");
    }  else {
        return null;
    }
    if(mediaFile == null){
        Log.d("AddRecipeActivity", "Media file is null");
    }
    return mediaFile;
}

当我打印我的 Uri 时(就在触发意图之前),我得到以下输出。

04-04 04:22:40.757 22402-22402/scissorkick.com.project2 D/AddRecipeActivity: file:///data/user/0/scissorkick.com.project2/files/NewFolder/IMG_20160404_042240.jpg

此外,当我检查目录是否已创建时,布尔值为真。 但是,当我的相机意图的 onActivityResult 运行时,结果代码为 0。

为什么它会在这一点上失败?我已经在清单中定义了适当的权限,并且还在运行时请求了外部存储写入权限。

编辑:添加 onActivityResult:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
    if(requestCode == CAMERA_REQUEST){
        Log.d("AddRecipe", String.valueOf(resultCode));
        if(resultCode == RESULT_OK){
            photo = (Bitmap) data.getExtras().get("data");
            thumb = ThumbnailUtils.extractThumbnail(photo, 240, 240);
            photoView.setImageBitmap(thumb);
            //Toast.makeText(getApplicationContext(), "image saved to:\n" + data.getData(), Toast.LENGTH_SHORT).show();
        }
        else{
            Toast.makeText(getApplicationContext(), "Fail", Toast.LENGTH_SHORT).show();
        }
    }
}

onActivityResult里面有一些乱码,关键是resultCode = 0,不知道为什么。

【问题讨论】:

  • 显示您的 onActivityResult 代码
  • 已添加。我认为它连接正确,但我不是 100%
  • 你的问题解决了吗??

标签: android android-intent android-camera


【解决方案1】:

在最后的活动中,输入以下代码

    data.putExtra("uri", uri);//uri = your image uri
    getActivity().setResult(""result_code", data);
    getActivity().finish();

然后在你的 onActivityResult 代码中你可以得到类似的 uri

Uri uri = data.getExtras().getParcelable("uri");

然后您可以使用此 Uri 值来检索您的图像。

【讨论】:

    【解决方案2】:

    这是我如何在我的应用中拍照的!

    当我按下自己的图像按钮时

    static final int REQUEST_IMAGE_CAPTURE = 1;
    static final int REQUEST_TAKE_PHOTO = 1
    static final String STATE_PHOTO_PATH = "photoPath";
    
    ImageButton photoButton = (ImageButton) this.findViewById(R.id.take_picture_button);
            photoButton.setOnClickListener(new View.OnClickListener() {
    
                @Override
                public void onClick(View v) {
                    dispatchTakePictureIntent();
                }
            });
    

    这里是如何管理和创建/存储带有图像的文件

    private File createImageFile() throws IOException {
            // Create an image file name
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            String imageFileName = "JPEG_" + timeStamp + "_";
            File storageDir = Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_PICTURES);
            File image = File.createTempFile(
                    imageFileName,  /* prefix */
                    ".jpg",         /* suffix */
                    storageDir      /* directory */
            );
    
            // Save a file: path for use with ACTION_VIEW intents
            mCurrentPhotoPath = "file:" + image.getAbsolutePath();
            return image;
        }
    
        //Create a new empty file for the photo, and with intent call the camera
        private void dispatchTakePictureIntent() {
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            // Ensure that there's a camera activity to handle the intent
            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                // Create the File where the photo should go
                File photoFile = null;
                try {
                    photoFile = createImageFile();
                } catch (IOException e) {
                    // Error occurred while creating the File
                    Log.e("Error creating File", String.valueOf(e.getMessage()));
                }
                // Continue only if the File was successfully created
                if (photoFile != null) {
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                            Uri.fromFile(photoFile));
                    //I have the file so now call the Camera
                    startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
                }
            }
        }
    
        private void openImageReader(String imagePath) {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            Uri imgUri = Uri.parse(imagePath);
            intent.setDataAndType(imgUri, "image/*");
            startActivity(intent);
    
        }
    

    在 ActivityResult 中,我只在数据库中保存了一条记录,其中包含图像的路径,以便我可以将其检索回来并读取像文件一样存储的照片。

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
    
                //Save the path of image in the DB
                db.addCompito(new Compiti(activity_name, null, mCurrentPhotoPath));
                refreshListView();
            }
        }
    

    如果你有一些屏幕旋转,别忘了添加类似

    @Override
        public void onSaveInstanceState(Bundle savedInstanceState) {
            // Save the user's current game state
            savedInstanceState.putString(STATE_PHOTO_PATH, mCurrentPhotoPath);
    
            // Always call the superclass so it can save the view hierarchy state
            super.onSaveInstanceState(savedInstanceState);
        }
    
    
        public void onRestoreInstanceState(Bundle savedInstanceState) {
            // Always call the superclass so it can restore the view hierarchy
            super.onRestoreInstanceState(savedInstanceState);
    
            // Restore state members from saved instance
            mCurrentPhotoPath = savedInstanceState.getString(STATE_PHOTO_PATH);
        }
    

    为什么?

    因为当旋转更改时,您可能会丢失您为“新照片”创建的文件,当您接受并保存它时,您的照片路径为空,并且不会创建任何图像。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-28
      • 1970-01-01
      • 2018-09-12
      • 2016-07-13
      • 1970-01-01
      相关资源
      最近更新 更多