首页 > 解决方案 > 我可以将安卓应用的照片保存在 SD 卡上吗?

问题描述

我正在构建一个应用程序来从相机拍照,但我不知道我可以将我的应用程序照片保存在 avd android 的 sd 卡上(我的 AVD:Nexus 5X API 26 Android 8.0)。我拍照并在我的应用程序上展示了我的照片,但我在为我的应用程序创建的文件夹中找不到它(在 SDCard 中)。谢谢你。

标签: androidandroid-cameraandroid-sdcardandroid-camera-intent

解决方案


首先在您的清单中添加权限:

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

所以你需要获取你的位图。你可以尝试从 ImageView 中获取它,例如:

BitmapDrawable drawable = (BitmapDrawable) mImageView1.getDrawable();
Bitmap bitmap = drawable.getBitmap();

您必须从 SD 卡进入目录

    File sdCardDirectory = Environment.getExternalStorageDirectory();
// Next, create your specific file for image storage:

    File image = new File(sdCardDirectory, "test.png");
//After that, you just have to write the Bitmap :

    boolean success = false;

    // Encode the file as a PNG image.
    FileOutputStream outStream;
    try {

        outStream = new FileOutputStream(image);
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream); 
        /* 100 to keep full quality of the image */

        outStream.flush();
        outStream.close();
        success = true;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (success) {
        Toast.makeText(getApplicationContext(), "Image saved with success",
                Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(getApplicationContext(),
                "Error during image saving", Toast.LENGTH_LONG).show();
    }

推荐阅读