将图像保存在外部存储中

时间:2017-10-28 15:41:17

标签: android android-studio

我的问题是,当我点击图片时,它会显示已保存的信息但是照片将不会被保存。我还允许访问外部存储空间WRITE_EXTERNAL_STORAGE

    public void onClick(View v) {
    if(isExternalStorageWriteable()) {
        FileOutputStream outputStream;
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
                R.drawable.img3);
        File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "MyImage.png");
        try {
                outputStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Toast.makeText(this,"Pic Created :  "+file,Toast.LENGTH_SHORT)
                .show();
    } else {
            Toast.makeText(this,"SDCard Not is Ready",Toast.LENGTH_SHORT)
                    .show(); } }
public boolean isExternalStorageWriteable()
{
    String state = Environment.getExternalStorageState();
    return Environment.MEDIA_MOUNTED.equals(state); }

enter image description here

1 个答案:

答案 0 :(得分:1)

"我还允许访问外部存储WRITE_EXTERNAL_STORAGE"在清单中还是您在运行时请求权限?

我猜您只在Android版> = 23(6.0)的设备上遇到此问题。 在执行此操作之前,您应该检查您是否有权在外部存储中写入,以防您应该获得许可:

ContextCompat.checkSelfPermission(thisActivity, Manifest.permission. WRITE_EXTERNAL_STORAGE);

ActivityCompat.requestPermissions(thisActivity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);

https://developer.android.com/training/permissions/requesting.html

如果授予了权限,请检查stacktrace并将其发布到此处,以确保" Pic Created" toast应该留在块末端的try-catch内,并且在catch块内部你必须启动负面吐司。