将图像保存到android中的库中

时间:2017-08-18 16:25:54

标签: android

如何保存相机进入图库的图像?我有这个代码,但不保存图像

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 = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName, /* prefix */
                ".jpg", /* suffix */
                storageDir /* directory */
        );

// Save a file: path for use with ACTION_VIEW intents
        mCurrentPhotoPath = image.getAbsolutePath();
        return image;
    }

几乎使用了一个

private void galleryAddPic() {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File f = new File(mCurrentPhotoPath);
        Uri contentUri = Uri.fromFile(f);
        mediaScanIntent.setData(contentUri);
        this.sendBroadcast(mediaScanIntent);
    }

但没有肯定的结果,在我的清单中我使用了这个权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="18"/>

1 个答案:

答案 0 :(得分:0)

从Android版M及以上版本,任何危险许可都需要运行时权限 - https://developer.android.com/guide/topics/permissions/requesting.html#normal-dangerous

public void checkPermissionGranted() {
    if (Build.VERSION.SDK_INT >= 23) {
        if (!(checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)) {
            requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
        }
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (!(grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
        Log.d(TAG, "Storage Permission not granted");   
    } else {
        // Permission granted - resume
    }
}