无法将图像保存在外部目录中

时间:2017-07-12 05:04:39

标签: java android fileoutputstream

我无法在我的Android应用程序中将图像保存在外部目录中。我练习自己并寻找同样的问题,但没有什么可以帮助我。 我想要做的就是显示一个包含该图像的对话框,并为用户提供一个保存选项,如果保存查看它。 但是它总是在out.flush()中捕获一个空指针异常;在棉花糖和鞋面。 在棒棒糖中工作正常。 权限已添加:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission-sdk-23 android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

代码对我来说似乎很好。任何帮助都将受到高度赞赏。

private void display_image(String url, String title) {

        Dialog dialog = new Dialog(MainActivity.this);
        dialog.setContentView(R.layout.dialog_display_images);
        dialog.setTitle(title);

        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
        layoutParams.copyFrom(dialog.getWindow().getAttributes());

        layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
        layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;

        dialog.show();
        dialog.getWindow().setAttributes(layoutParams);

        ImageView iv = (ImageView)dialog.findViewById(R.id.image_here);
        final InputStream in;
        Bitmap img=null;
        final Bitmap imgcpy;

        try {
            in = getAssets().open(url);
            img = BitmapFactory.decodeStream(in);
            iv.setImageBitmap(img);

        } catch (IOException e) {
            e.printStackTrace();
        }

        imgcpy = img;

        final FloatingActionButton save = (FloatingActionButton)dialog.findViewById(R.id.fab_save);
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final String filePath = Environment.getExternalStorageDirectory().toString();
                File dir = new File(filePath + "/app_images");
                dir.mkdirs();
                Random generate = new Random();
                int n = 10000;
                n = generate.nextInt(n);
                String fName = "Image-" + n + ".jpg";

                final File file = new File(dir, fName);
                if (file.exists()) {
                    file.delete();
                }
                try {
                    FileOutputStream out = new FileOutputStream(file);
                    imgcpy.compress(Bitmap.CompressFormat.JPEG, 90, out);
                    out.flush();
                    out.close();
                    new AlertDialog.Builder(MainActivity.this)
                            .setTitle("Image Saved Successfully")
                            .setIcon(R.drawable.ic_save)
                            .setMessage("Image saved at: " + file.getAbsolutePath())
                            .setNeutralButton("OK", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            })
                            .setPositiveButton("Open", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Toast.makeText(getApplicationContext(), "Opening...", Toast.LENGTH_SHORT).show();
                                    Intent intent = new Intent(Intent.ACTION_VIEW);
                                    intent.setDataAndType(Uri.parse("file://" + file.getAbsolutePath()), "image/*");
                                    startActivity(intent);
                                }
                            })
                            .create().show();
                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(MainActivity.this, "Could not save image", Toast.LENGTH_SHORT).show();
                } catch (NullPointerException e) {
                    Toast.makeText(MainActivity.this, "Could not save image", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

3 个答案:

答案 0 :(得分:0)

API级别6.0或以上,您需要运行时权限:

if (ContextCompat.checkSelfPermission(context,
        android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(MainActivity.this,
            new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_EXT_STORAGE);
}

并在您的活动中覆盖此方法:

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode) {
        case Constant.REQUEST_CODE_ASK_PERMISSIONS:
            if (grantResults!=null) {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    //Call ur save method here 
                } else {
                   Toast.makeText(this, "Please enable write permission from ,Toast.LENGTH_SHORT).show(); 

                }
            }
            break;
        default:
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}

答案 1 :(得分:0)

在Marshmallow及其上面的Api中,您需要检查权限运行时间

请求权限

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

获取结果onRequestPermissionsResult

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case 1: {

          // If request is cancelled, the result arrays are empty.
          if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // permission was granted, yay! Do the save image stuff

            } else {
                // permission denied, boo! Disable the

                Toast.makeText(this, "Permission denied to read your External storage", Toast.LENGTH_SHORT).show();
            }
            return;
        }
    }
}
 save.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                  if(permissionisnotgranted){
                       ActivityCompat.requestPermissions(mActivity,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        1);
                 }
                 else
                  {
                     //do stuff for save image
                   }
                }
    });

答案 2 :(得分:0)

使用此方法创建目录和图像文件:

private File createImageFile() throws IOException {

    // Create an image file name
    Random generate = new Random();
    int n = 10000;
    n = generate.nextInt(n);

    String nValue = String.valueOf(n);
    String fName = "Image-" + n;


    String filePath = Environment.getExternalStorageDirectory().toString();
    File dir = new File(filePath + "/app_images");

    if (!dir.exists()) {
        dir.mkdirs();
    }

    File image = File.createTempFile(
            fName,          /* prefix */
            ".jpg",         /* suffix */
            dir             /* directory */
    );

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = image.getAbsolutePath();
    Log.e("mCurrentPhotoPath", mCurrentPhotoPath + "  ++++"); //Prints you the image file path
    return image;
}

并在任何地方调用上述方法:

try {
     //photoFile = createImageFile();
     File photoFile = createImageFile();
} catch (IOException ex) {
  // Error occurred while creating the File
  ex.printStackTrace();
  Log.e("IO_EX", ex + "");
}

在清单中给出这些权限:

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

一切顺利!