无法将图像存储到内部存储

时间:2018-04-10 06:24:21

标签: android

您好我之前已经问过这个问题,但是我无法让这段代码发挥作用。我想将从相机捕获的图像保存到内部存储器中,以便用户无法访问。我的代码如下:

 private String saveToInternalStorage(Bitmap bitmapImage){
    ContextWrapper cw = new ContextWrapper(getApplicationContext());
    // path to /data/data/yourapp/app_data/imageDir
    File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
    // Create imageDir
    File mypath=new File(directory,"profile.jpg");

    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(mypath);
        // Use the compress method on the BitMap object to write image to the OutputStream
        bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return directory.getAbsolutePath();
}

我使用以下代码通过将先前获得的路径传递给此方法来获取图像的uri。

private Uri loadImageFromStorage(String path)
{


        File f=new File(path, "profile.jpg");
   Uri uri = Uri.parse(f.toString());


    return uri;
 }

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

试试这个,我也像你一样使用时会出错

 private String savePicture(Activity context, Bitmap bitmapImage) throws IOException {
    File mediaStorageDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + context.getString(R.string.app_name) + "/");
    if (!mediaStorageDir.exists()) {
        boolean b = mediaStorageDir.mkdir();
    }
    File imageToUpload = new File(mediaStorageDir.getAbsolutePath() + File.separator + new Date().getTime() + ".png");
    if (!imageToUpload.exists())
        imageToUpload.createNewFile();

    try {
        FileOutputStream out = new FileOutputStream(imageToUpload);
        bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, out);
        out.flush();
        out.close();
        bitmapImage.recycle();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return imageToUpload.getAbsolutePath();
}

答案 1 :(得分:0)

试试这个 它将文件存储在内部存储中,无需许可

如果回答有帮助,请发表评论

 private String saveToInternalStorage(Bitmap bitmapImage){
        ContextWrapper cw = new ContextWrapper(getApplicationContext());
        // path to /data/data/yourapp/app_data/imageDir
        // Create imageDir
        File mypath=new File(getFilesDir(),"profile.jpg");

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(mypath);
            // Use the compress method on the BitMap object to write image to the OutputStream
            bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return mypath.getAbsolutePath();
    }