简体   繁体   English

Android:在外部存储设备上保存图像的最佳方法

[英]Android: Best way to save image at external Storage

When i'm trying to save an image at some devices the app crashes. 当我尝试在某些设备上保存图像时,应用程序崩溃。 After some research i think the problem is the imageRoot, but i'm kind of lost with so many solutions... I think the problem is about obtaining external storage path. 经过一番研究,我认为问题是imageRoot,但是我迷失了这么多解决方案……我认为问题在于获取外部存储路径。 The device i'm using to test my app doesn't have any sd card, the path is /mnt/sdcard/Pictures and the image is being saved successfully. 我用来测试我的应用程序的设备没有任何SD卡,路径为/mnt/sdcard/Pictures ,并且图像已成功保存。 I want it to work whether phone has an sd card or not. 无论手机是否具有SD卡,我都希望它能正常工作。 Thanks for any help in advance. 感谢您的任何帮助。

imageRoot=new File(Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES), "AppName");

private void saveImage() {


        Bitmap bitmap = sqimage.getDrawingCache();
        File image = new File(imageRoot, imageName);



        if (image.exists()) {
            image.delete();

        }

        try {
            FileOutputStream output = new FileOutputStream(image);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, output);
            output.flush();
            output.close();
            new SingleMediaFileConnector(getActivity().getApplicationContext(), image);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            success = false;
        } catch (IOException e) {
            e.printStackTrace();
            success = false;
        }
  }

Sometimes getExternalStoragePublicDirectory path doesn't exist. 有时getExternalStoragePublicDirectory路径不存在。 You need to check for its existence. 您需要检查其存在。

try {
    imageRoot=new File(Environment.getExternalStoragePublicDirectory(
        Environment.DIRECTORY_PICTURES), "AppName");
    File image = new File(imageRoot, imageName);

    // Make sure the Pictures directory exists.
    imageRoot.mkdirs();

    // Other stuffs here

} catch (IOException e) {
    // Unable to create file, likely because external storage is
    // not currently mounted.
    Log.w("ExternalStorage", "Error writing " + file, e);
}

See here for more details. 有关更多详细信息,请参见此处

[Edit] [编辑]
An alternate way can be use: 可以使用另一种方法:

getExternalFilesDir(Environment.DIRECTORY_PICTURES);

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

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