简体   繁体   English

我尝试使用Android Studio在我的SD卡中保存位图图像

[英]I try save bitmap image in my SDcard using android studio

Please help me to solve this problem in my code ,I would like to save the bitmap image (newimage) into SD card in my phone (Galaxy j7), but I get the error (no such file or directory) 请在代码中帮助我解决此问题,我想将位图图像(newimage)保存到手机(Galaxy j7)的SD卡中,但出现错误(没有此类文件或目录)

File filepath;
    filepath = Environment.getExternalStorageDirectory();

   File  dir = new File(filepath.getAbsolutePath()+"/save image");
    dir.mkdirs();
    File  file = new File(dir,"myimage.png");
    Toast.makeText(MainActivity.this,"image saved to SD",Toast.LENGTH_LONG).show();
   try{

        OutputStream stream ;

        stream = new FileOutputStream(file);

        newimage.compress(Bitmap.CompressFormat.PNG,100,stream);

        stream.flush();

        stream.close();

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

    // Parse the saved image path to uri
    Uri savedImageURI = Uri.parse(filepath.getAbsolutePath());

    // Display the saved image to ImageView
  //  imagev.setImageURI(savedImageURI);

    // Display saved image uri to TextView
    tv_saved.setText("Image saved in external storage.\n" + savedImageURI);

the error message is : 错误消息是:

W/System.err: java.io.FileNotFoundException: /storage/emulated/0/save image/myimage.png (No such file or directory)

I added the permission of write in manifest.xml as follow: 我在manifest.xml中添加了写入权限,如下所示:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
    android:maxSdkVersion="21" />
<uses-sdk
            android:minSdkVersion="9"
    android:targetSdkVersion="21"/>

I think there is no problem with your codes, the problem is the version of Android that you are compiling your project on. 我认为您的代码没有问题,问题在于您要在其上编译项目的Android版本。 On higher versions of the Android you should implement runtime permission for storage permission. 在更高版本的Android上,您应该为存储权限实现运行时权限。

Refer to the answer here which is going to solve your problem. 请参阅此处的答案它将解决您的问题。

Edit: There is another problem with your implementation that I recognized after posting my answer. 编辑:发布您的答案后,我认识到您的实现的另一个问题。 Before trying to save your image on the directory named save image you should create this folder by implementing 在尝试将图像保存到名为save image的目录之前,应通过以下方式创建此文件夹

String folder_main = "save image"; File f = new File(Environment.getExternalStorageDirectory(), folder_main); if(!f.exists()) {f.mkdirs();}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM