Android:捕获和存储图片

标签 android file-io android-permissions

我正在关注 this tutorial拍照、显示缩略图和将完整图片存储在仅供我的应用程序使用的本地公共(public)存储中。

问题:尝试访问我的应用程序的本地存储时 EACCESS(权限被拒绝)

11-12 10:36:30.765    3746-3746/com.test.example.photo W/System.err﹕ java.io.IOException: open failed: EACCES (Permission denied)
11-12 10:36:30.765    3746-3746/com.test.example.photo W/System.err﹕ at java.io.File.createNewFile(File.java:948)
11-12 10:36:30.765    3746-3746/com.test.example.photo W/System.err﹕ at java.io.File.createTempFile(File.java:1013)

我看过this question但它似乎已经过时,因为今天没有任何解决方案有效。 This question也没有提供有效的解决方案。我见过和尝试过的其他结果和解决方案似乎只是模糊相关。

我的 list 权限

</application>
    <!-- PERMISSIONS -->
    <permission
        android:name="android.hardware.Camera.any"
        android:required="true" />
    <permission
        android:name="android.permission.WRITE_EXTERNAL_STORAGE"
        android:required="true" />
    <!-- android:maxSdkVersion="18" seemingly does nothing-->
</manifest>

崩溃的方法

private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";

    //THIS IS WHERE IT CRASHES
    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;
}

我正在使用 i9250 Galaxy Nexus 3 手机来运行示例,因为我的模拟器没有摄像头并且会自动删除元素。我的目标 SDK 是 16,我已将我的构建工具和 Android Studio 更新到最新版本。

我觉得我在这里遗漏了一些明显的东西,因为拍照在应用程序中很常见,我无法想象它对每个人都不起作用,但我被困住了,我很感激你的指导。我是 android 的新手,我主要使用的文献是 Beginning Android 4 Game Programming、Beginning Android 4 和 Pro Android 4。

感谢您的宝贵时间!

最佳答案

感谢大家的帮助,现在可以了!

显然我使用的是需要权限的 SD 卡存储,如 permission vs uses-permisson 中所述。而不是从 API 级别 19 开始不需要任何权限的本地沙盒存储。

SD卡访问,需要写权限:Environment.getExternalStoragePublicDirectory

您应用的沙盒本地存储:getExternalFilesDir

我将此代码用于 API 级别 16,实现和更改所需的工作量应该很小,但如果您遇到问题,请留言,我会尽力提供帮助或澄清。

大部分解释都在代码中作为注释

    //OnClick hook, requires implements View.OnClickListener to work
    public void takePicture(View v) {
        dispatchTakePictureIntent();
    }

    private void dispatchTakePictureIntent() {
        //Create intent to capture an image from the camera
        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 directory File where the photo should go, do NOT try to create the image file itself
            File photoFile = null;
            try {
                //mCurrentPhotoPath is a File outside of the methods, so all methods know the last directory for the last picture taken
                mCurrentPhotoPath = createImageFile();
                photoFile = mCurrentPhotoPath;
            } catch (IOException ex) {
                // Error occurred while creating the File
                ex.printStackTrace();
            }
            // Continue only if the File was successfully created
            if (photoFile != null) {
                //photoFile MUST be a directory or the camera will hang on an internal
                //error and will refuse to store the picture,
                //resulting in not being able to to click accept
                //MediaStore will automatically store a jpeg for you in the specific directory and add the filename to the path
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            //unique name, can be pretty much whatever you want
            imageId = generateImageId(); 
            //Get file.jpg as bitmap from MediaStore's returned File object
            Bitmap imageBitmap = BitmapFactory.decodeFile(mCurrentPhotoPath.getAbsolutePath()); 
            //resize it to fit the screen
            imageBitmap = Bitmap.createScaledBitmap(imageBitmap,300,300,false); 
            //Some ImageView in your layout.xml
            ImageView imageView = (ImageView)findViewById(R.id.imageView); 
            imageView.setImageBitmap(imageBitmap);
            Bitmap thumbnail =  makeThumbnail(mCurrentPhotoPath);
            ImageView thumbnail = (ImageView)findViewById(R.id.thumbnail); 
            thumbnail.setImageBitmap(imageBitmap);
        }
    }

    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        //completely optional subdirectory structure
        storageDir = new File(storageDir, "custom_directory");
        return storageDir;
    }    

    private Bitmap makeThumbnail(File currentPhotoPath) {
        // Get the dimensions of the View, I strongly recommend creating a <dimens> resource for dip scaled pixels
        int targetW = 45;
        int targetH = 80;

        // Get the dimensions of the bitmap
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(currentPhotoPath.getAbsolutePath(), bmOptions);
        int photoW = bmOptions.outWidth;
        int photoH = bmOptions.outHeight;

        // Determine how much to scale down the image
        int scaleFactor = Math.min(photoW/targetW, photoH/targetH);

        // Decode the image file into a Bitmap sized to fill the View
        bmOptions.inJustDecodeBounds = false;
        bmOptions.inSampleSize = scaleFactor;
        bmOptions.inPurgeable = true;

        Bitmap bitmap = BitmapFactory.decodeFile(currentPhotoPath.getAbsolutePath(), bmOptions);
        return bitmap;
    }

    private long generateImageId() {
        return Calendar.getInstance().getTimeInMillis();
    }

Android 5.0,API 21,将使用 Camera2 API,据我所知,所有这些都将隐藏得很远。你可以阅读它here

关于Android:捕获和存储图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26884556/

相关文章:

android - 在 SQLite 中更改表的主键

android - 通过线程中的处理程序更新主 Activity 中的 UI (Android)

java - 用哨兵填充字符串数组

android - Android 中的权限存储在哪里?

java - libgdx 滚动 Pane 不显示

java.io.FileNotFoundException(尝试反序列化)

你能从c中的文件中的特定位置写入吗?

c++ - ifstream 总是返回 "ELF"给对象

Android 如何显示前置摄像头(仅适用于镜像)

android - 我可以删除此权限吗? (在 Android 5.0 设备中会导致 INSTALL_FAILED_DUPLICATE_PERMISSION)