Search code examples
androidandroid-cameraandroid-sdcardandroid-camera-intent

Can I save photo of android app on sd card?


I'm building an app to take picture from camera but I don't know that I can save my photo of my app on sd card in avd android (my AVD: Nexus 5X API 26 Android 8.0). I took photo and showed my photo on my app but I can't find it in my folder I created for my app (in SDCard). Thank you.


Solution

  • first add the permission in your Manifest:

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

    and so you need to get your Bitmap.you can try to get it from the ImageView such as:

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

    you must get to directory from SD Card

        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();
        }