Search code examples
androidandroid-studioandroid-imageviewfilenotfoundexceptioninternal-storage

Save the image from an ImageView(captured from camera) in my custom defined folder in the INTERNAL MEMORY


I have been referring various posts and sites and I have been trying this since 3 days and I cannot figure this out!

My Activity has 2 buttons! First one is Capture and second one is Save. On pressing the capture button, I need to launch the camera and then when we click the picture and click on OK., the image is set to the ImageView in the activity. Now, when I click on the save button., I need to save the image in the internal memory in my own folder which must appear in the File explorer. Say MyCustomFolder>Pictures>MyCapture.jpg

I have tried several examples but what I was able to do in one case was to store images in default directories such as Downloads or DCIM or PICTURES.

In other case, I was able to store the picture in Android>data>com.example.shravan.camera>files>Pictures>myImage.jpg

In the case I am posting here, I am able to save the image in /data/user/0/com.example.shravan.asbdbsadbsabcxscsa/app_mydir/myfile

Here I have one more method saveFile which is being commented as I am getting FileNotFound exception as always!

However, I am not able to save in my own customfolder. Please check the code and help me and let me know if I am missing something!

Code:

MainActivity.java

package com.example.shravan.asbdbsadbsabcxscsa;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;    
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {
    Uri imageUri;
    private static final String TAG = "abc";
    static final int REQUEST_IMAGE_CAPTURE =1 ;
    ImageView iv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        iv = (ImageView)findViewById(R.id.myIV);
    }

    public void Capture(View v){
        Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(i,REQUEST_IMAGE_CAPTURE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    {
        if(requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK)
        {
            print("in onAC");
            imageUri=data.getData();
            iv.setImageURI(imageUri);
        }
    }

    public void savee(View v){
        Context context =this;
        BitmapDrawable drawable = (BitmapDrawable) iv.getDrawable();
        Bitmap bitmap = drawable.getBitmap();
        File mydir = context.getDir("mydir", Context.MODE_PRIVATE); 
        File fileWithinMyDir = new File(mydir, "myfile"); 
        try {
            FileOutputStream fos = new FileOutputStream(fileWithinMyDir);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            print("path is"+fileWithinMyDir.getAbsolutePath());
            fos.flush();
            fos.close();
        }
        catch (FileNotFoundException e) 
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    public void saveFile(View v){
        Context context =this;
        BitmapDrawable drawable = (BitmapDrawable) iv.getDrawable();
        Bitmap bitmap = drawable.getBitmap();
        File mydir = context.getFilesDir();
        String filename = "Arunachala/Shravan/Images/MyImage.jpg";
        File file = new File(mydir, filename);       
        file.mkdirs();     
        print("path is"+file.getAbsolutePath());
        try {
            FileOutputStream fos = new FileOutputStream(file);
            print("path is"+file.getAbsolutePath());
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        }
        catch (FileNotFoundException e) {
            e.printStackTrace();
        } 
        catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void print(String s){
        Log.d(TAG, s);
    }

}

This is my content_main.xml file: content_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.example.shravan.asbdbsadbsabcxscsa.MainActivity"
tools:showIn="@layout/activity_main">

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/myIV"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="175dp" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Capture"
    android:id="@+id/myB"
    android:onClick="Capture"
    android:layout_alignParentBottom="true"
    android:layout_toStartOf="@+id/myIV" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="save"
    android:id="@+id/button"
    android:layout_alignParentBottom="true"
    android:layout_toEndOf="@+id/myB"
    android:onClick="savee" />
</RelativeLayout>

This is my AndroidManifest.xml file: AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.shravan.asbdbsadbsabcxscsa">

<uses-feature android:name="android.hardware.Camera"       android:required="true"></uses-feature>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

</manifest>

My latest logcat:

08-09 14:28:38.889 12727-12727/com.example.shravan.asbdbsadbsabcxscsa D/abc: path is/data/user/0/com.example.shravan.asbdbsadbsabcxscsa/app_mydir/myfile

Please help!


Solution

  • Got it working:

    Code for saving:

        FileOutputStream outStream = null;
        File sdCard = Environment.getExternalStorageDirectory();
        File dir = new File(sdCard.getAbsolutePath() + "/camtest");
        dir.mkdirs();
        String fileName = String.format("%d.jpg", System.currentTimeMillis());
        File outFile = new File(dir, fileName);
        outStream = new FileOutputStream(outFile);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
        outStream.flush();
        outStream.close();
        refreshGallery(outFile);
    

    Permissions:

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

    Finally:

    Go to Device Settings>Device>Applications>Application Manager>"your app">Permissions>Enable Storage permission!