0

我只想在手机的 Imagefolder 中保存一张图片。我有两个我试过的例子。

1. 示例

当我激活 onClick 方法时,我的应用程序崩溃:

public void onClick(View arg0) {

        Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

        startActivityForResult(cameraIntent, 1337);
}});

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

     if( requestCode == 1337)
            {
                Bitmap thumbnail = (Bitmap) data.getExtras().get("data");

MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());

            }
            else 
            {
                Toast.makeText(AndroidCamera.this, "Picture NOt taken", Toast.LENGTH_LONG);
            }
            super.onActivityResult(requestCode, resultCode, data);
        }

2. 例子

在我用 Uri 保存拍摄的照片之前。但它把我的照片保存在一个文件夹中,我只能在我的 PC 或 FileApp 上访问。我不知道如何将 Uri 的路径方向更改为手机中现有的默认图像文件夹。

Uri uriTarget = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI,  new ContentValues());
4

1 回答 1

1

这就是我将图像保存到指定图像文件夹的方式

启动相机意图时,我定义了路径和目录,我的图像应该保存在哪里,并在启动相机时将其作为 intetn extra 传递:

    private void startCameraIntent() {
        //create file path
        final String photoStorePath = getProductPhotoDirectory().getAbsolutePath();

        //create file uri
        final Uri fileUri = getPhotoFileUri(photoStorePath);

        //create camera intent
        final Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        //put file ure to intetn - this will tell camera where to save file with image
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        // start activity
        startActivityForResult(cameraIntent, REQUEST_CODE_PHOTO_FROM_CAMERA);

        //start image scanne to add photo to gallery
        addProductPhotoToGallery(fileUri);
    }

以下是上面代码中使用的一些辅助方法

    private File getProductPhotoDirectory() {
        //get directory where file should be stored
        return new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES),
                "myPhotoDir");
    }

    private Uri getPhotoFileUri(final String photoStorePath) {

        //timestamp used in file name
        final String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
              Locale.US).format(new Date());

        // file uri with timestamp
        final Uri fileUri = Uri.fromFile(new java.io.File(photoStorePath 
              + java.io.File.separator + "IMG_" + timestamp + ".jpg"));

        return fileUri;
    }

    private void addProductPhotoToGallery(Uri photoUri) {
        //create media scanner intetnt
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);

        //set uri to scan
        mediaScanIntent.setData(photoUri);
        //start media scanner to discover new photo and display it in gallery
        this.sendBroadcast(mediaScanIntent);
   }
于 2013-08-07T17:14:45.597 回答