将图像文件保存到特定目录

时间:2014-11-10 17:53:22

标签: android android-gallery

我正在构建一个访问相机的Android应用程序,但我想将图像保存到特定的文件夹,但我不知道如何去做。我使用URI构建器吗?

这是我必须从相机获取图像的代码。

Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
    File photo = new File(Environment
                    .DIRECTORY_PICTURES), "pic.jpg");
    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
    imageUri = Uri.fromFile(photo);
    startActivityForResult(intent, TAKE_PICTURE);

1 个答案:

答案 0 :(得分:3)

您可以在自己的目录中创建一个文件,如下所示:

private File openFileFromMyDirectory() {

    File imageDirectory = null;
    String storageState = Environment.getExternalStorageState();
    if (storageState.equals(Environment.MEDIA_MOUNTED)) {
        imageDirectory = new File(
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "com.myapp.camera");
        if (!imageDirectory.exists() && !imageDirectory.mkdirs()) {
            imageDirectory = null;
        } else {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault());

            return new File(imageDirectory.getPath() +
                    File.separator + "IMG_" +
                    dateFormat.format(new Date()) + ".jpg");
        }
    }
    return null;
}

然后从uri获取位图:

Bitmap mCameraBitmap= MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);

最后将位图保存到文件中

private void saveImageToFile(File file) {

    if (mCameraBitmap != null) {
        FileOutputStream outStream = null;
        try {
            outStream = new FileOutputStream(file);
            if (!mCameraBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream)) {
                Toast.makeText(this, "Unable to save image to file.",
                        Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(this, "Saved image to: " + file.getPath(),
                        Toast.LENGTH_LONG).show();
            }
            outStream.close();
        } catch (Exception e) {
            Toast.makeText(this, "Unable to save image to file.",
                    Toast.LENGTH_LONG).show();
        }
    }
}