如何拍摄照片并将其保存在图库中可见的应用程序的自定义文件夹中

时间:2014-06-26 11:51:13

标签: android android-gallery android-camera-intent

我已经在这几天挣扎了这个问题,而在stackoverflow上发布类似问题的其他答案对我没有帮助。

我想要做的是将自定义ArrayAdapter设置为ListView,在此适配器中,我想将onClickListener设置为出现在每个项目中的按钮。然后我希望用户选择是否要用相机拍照或从图库中选择一张图片。然后我希望图片保存在Gallery内的应用程序自己的文件夹中。但是,尽管在Gallery中创建并显示了自定义文件夹,但图片本身存储在Camera文件夹中,我可以在自定义文件夹中看到损坏的文件。

我已经在devsite http://developer.android.com/training/camera/photobasics.html上阅读了photobasics,但它并没有多大帮助。 我在Fragment中实现了onActivityResult,但是Uri路径与适配器中创建的路径不同。

以下是代码:

  • 在ArrayAdapter中:

    photoPicker.setOnClickListener(new View.OnClickListener()
    {
        @Override public void onClick(View v)
        {
    
            // Camera.
            final List<Intent> cameraIntents = new ArrayList<Intent>();
            final Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            final PackageManager packageManager = mContext.getPackageManager();
            final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
            for (ResolveInfo res : listCam)
            {
                final String packageName = res.activityInfo.packageName;
                final Intent intent = new Intent(captureIntent);
                intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
                intent.setPackage(packageName);
                cameraIntents.add(intent);
            }
    
            // Filesystem.
            final Intent galleryIntent = new Intent();
            galleryIntent.setType("image/*");
            galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
    
            // Chooser of filesystem options.
            final Intent chooserIntent = Intent.createChooser(galleryIntent, "Vyber zdroj");
    
            // Add the camera options.
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));
    
            if (chooserIntent.resolveActivity(mContext.getPackageManager()) != null)
            {
                // Create the File where the photo should go
                File photoFile = null;
                try
                {
                    photoFile = createImageFile();
                }
                catch (IOException ex)
                {
                    // Error occurred while creating the File
    
                }
                // Continue only if the File was successfully created
                if (photoFile != null)
                {
                    chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                                           Uri.fromFile(photoFile));
                    Log.i(TAG,"uri from file:"+Uri.fromFile(photoFile).toString());
                    chooserIntent.putExtra("path",mCurrentPhotoPath);
                    fragment.startActivityForResult(chooserIntent, FlowListUtils.getIdFromDate(experience.getDate()));
                }
            }
        }
    });
    
    
     private File createImageFile() throws IOException
    {
    
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    String storagePath = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES).getPath()+"/MyApp";
    
    File storageDir = new File(storagePath);
    storageDir.mkdirs();
    
    File image = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
    );
    
    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = "file:" + image.getAbsolutePath();
    Log.i(TAG,"mCurrent Photo Path in adapter:"+mCurrentPhotoPath);
    return image;
    }
    
  • 此代码位于我的片段

     @Override public void onActivityResult(int requestCode, int resultCode, Intent data)
     {
    super.onActivityResult(requestCode, resultCode, data);
    
    ExperienceAdapter.dateForPicture = requestCode;
    ExperienceAdapter.uriForPicture = data.getData();
    
    
    galleryAddPic(path);
    }
    
    
    private void galleryAddPic(String path)
    {
    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    File f = new File(ExperienceAdapter.mCurrentPhotoPath);
    
    Uri contentUri = Uri.fromFile(f);
    mediaScanIntent.setData(contentUri);
    getActivity().sendBroadcast(mediaScanIntent);
    }
    

我添加到intent的路径是file:/storage/emulated/0/Pictures/MyApp/JPEG_20140626_133228_1332202116.jpg 但突然改变内容:// media / external / images / media / 6273在Intent中返回onActivityResult。

我哪里错了?

2 个答案:

答案 0 :(得分:1)

以下是保存图像的功能

public static String saveImageInExternalCacheDir(Context context, Bitmap bitmap, String myfileName) {
    String fileName = myfileName.replace(' ', '_') + getCurrentDate().toString().replace(' ', '_').replace(":", "_");
    String filePath = (context.getExternalCacheDir()).toString() + "/" + fileName + ".jpg";
    try {
        FileOutputStream fos = new FileOutputStream(new File(filePath));
        bitmap.compress(Bitmap.CompressFormat.JPEG, 85, fos);
        fos.flush();
        fos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return filePath;
}

答案 1 :(得分:0)

这里有一个很好的例子 - &gt; Taking Photos Simply

使用createImageFile功能保存时,您可以选择目录网址:

private File createImageFile() throws IOException {
// Create an image file name
timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
        Environment.DIRECTORY_PICTURES);]
File image = File.createTempFile(
    imageFileName,
    ".jpg",
    storageDir
);
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}

我认为这就是你所需要的!