无法将位图图像保存在我的画廊中

时间:2018-06-27 14:48:26

标签: java android

我有一个片段显示相机,当用户单击主按钮时,会拍摄一张照片。我试图在图库中创建一个路径并将图像保存在那里,但是每次在模拟器中打开图库时,都没有包含图像的文件夹。您知道什么可能导致此问题吗?这是我的代码:

创建路径并保存图像的代码

private void saveImage(Bitmap finalBitmap, String image_name) {

   final String appDirectoryName = "/Feel/";
   String root = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES).toString() + appDirectoryName;
     File myDir = new File(root);
    myDir.mkdirs();
    String fname = "Image-" + image_name + ".jpg";
    File file = new File(myDir, fname);
    if (file.exists()) file.delete();
    Log.i("LOAD", root + fname);
    try {
        FileOutputStream out = new FileOutputStream(file);
        finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.flush();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

1 个答案:

答案 0 :(得分:0)

改为使用此代码

private void saveImage(Bitmap finalBitmap, String image_name) {
     try {

            FileOutputStream outStream = null;
            File sdCard = Environment.getExternalStorageDirectory();
            File dir = new File(sdCard.getAbsolutePath() + "/YourFolderName");
            dir.mkdirs();
            String fileName = String.format("%d.jpg", image_name);
            File outFile = new File(dir, fileName);
            outStream = new FileOutputStream(outFile);
            finalBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
            outStream.flush();
            outStream.close();
                Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
}

并且不要忘记添加对外部存储器进行读写的权限
看到这个更多的细节 Permission denied on writing to external storage despite permission