1

I am newbie to native android development. I am working on android studio and initializes tabbed activity. First tab is for map second tab is for camera. For camera i am using image view and a button that will open the camera. For now i am able to see the current image taken in image view but i want to save it into my internal/external device storage. For this i have searched many articles which are below.

  1. Link 1
  2. Link 2
  3. Link 3

But couldn't find a good solution. Moreover i am using fragments to do this. Below is my manifest.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.accurat.faisal">

<permission android:name="com.example.accurat.faisal.permission.MAPS_RECEIVE"
    android:protectionLevel="signature"/>

<uses-permission android:name="com.example.accurat.faisal.permission.MAPS_RECEIVE"/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.hardware.camera"/>
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>



<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true"
    />


<application
     android:name="android.support.multidex.MultiDexApplication"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="MY_KEY"
        />

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
    <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>

Below is my layout for camera

<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"
tools:context="com.example.accurat.faisal.MainActivity$PlaceholderFragment">


<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:srcCompat="@android:drawable/ic_menu_camera"
    android:id="@+id/imageView"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_above="@+id/getpicture" />

<Button
    android:id="@+id/getpicture"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Take Picture"
    android:layout_marginBottom="52dp"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" /></RelativeLayout>

Below is my java code for taking image

public class Camera extends Fragment {

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 1888;
public static final int REQUEST_CAMERA = 1;
Button button;
ImageView imageView;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
  final View rootView = inflater.inflate(R.layout.camera, container, false);

    button = (Button)rootView.findViewById(R.id.getpicture);
    imageView = (ImageView)rootView.findViewById(R.id.imageView);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Check permission for CAMERA
            if (ActivityCompat.checkSelfPermission(getActivity(), CAMERA)
                    != PackageManager.PERMISSION_GRANTED) {

                // Check Permissions Now
                // Callback onRequestPermissionsResult interceptado na Activity MainActivity
                ActivityCompat.requestPermissions(getActivity(),
                        new String[]{CAMERA},
                        Camera.REQUEST_CAMERA);

            }
            else {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE );

            }


        }
    });



    return rootView;
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
    {
        if (resultCode == Activity.RESULT_OK)
        {
            Bitmap bmp = (Bitmap)data.getExtras().get("data");
            ByteArrayOutputStream stream = new ByteArrayOutputStream();

            bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
            byte[] byteArray = stream.toByteArray();

            // convert byte array to Bitmap

            Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0,
                    byteArray.length);

            imageView.setImageBitmap(bitmap);

        }
    }
}

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case REQUEST_CAMERA: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // contacts-related task you need to do.
                Toast.makeText(getContext(), "Permission granted", Toast.LENGTH_SHORT).show();
            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
                Toast.makeText(getContext(), "Permission denied", Toast.LENGTH_SHORT).show();
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}}

Bellow are my includes

import static android.Manifest.permission.CAMERA;
import static android.Manifest.permission.RECORD_AUDIO;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import static android.Manifest.permission.READ_EXTERNAL_STORAGE;

I have studied how to save image but couldn't understand it well. I am surely missing something that i don't know

Any help would be highly appreciated

Community
  • 1
  • 1
Moeez
  • 494
  • 9
  • 55
  • 147

3 Answers3

5

try this code in your onActivityResult()

if(isStoragePermissionGranted()){
    SaveImage(bitmap)
    }

For saving the image:

 private void SaveImage(Bitmap finalBitmap) {

    String root = Environment.getExternalStorageDirectory().toString();
    File myDir = new File(root + "/saved_images");    
    myDir.mkdirs();
    Random generator = new Random();
    int n = 10000;
    n = generator.nextInt(n);
    String fname = "Image-"+ n +".jpg";
    File file = new File (myDir, fname);
    if (file.exists ()) file.delete (); 
    try {
           FileOutputStream out = new FileOutputStream(file);
           finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
           out.flush();
           out.close();

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

use this method for permission check:

    public  boolean isStoragePermissionGranted() {
    if (Build.VERSION.SDK_INT >= 23) {
        if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
            Log.v(TAG,"Permission is granted");
            return true;
        } else {

            Log.v(TAG,"Permission is revoked");
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 2);
            return false;
        }
    }
    else { //permission is automatically granted on sdk<23 upon installation
        Log.v(TAG,"Permission is granted");
        return true;
    }
}

For getting the result:

 @Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case REQUEST_CAMERA: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // contacts-related task you need to do.
                Toast.makeText(getContext(), "Permission granted", Toast.LENGTH_SHORT).show();
            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
                Toast.makeText(getContext(), "Permission denied", Toast.LENGTH_SHORT).show();
            }
            return;
        }

        case 2: {

            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(getContext(), "Permission granted", Toast.LENGTH_SHORT).show();
                SaveImage(bitmap);
            } else {
                Toast.makeText(getContext(), "Permission denied", Toast.LENGTH_SHORT).show();
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
 }
rafsanahmad007
  • 23,683
  • 6
  • 47
  • 62
0

First of all your your onActivityResult is messed up, You don't need to convert Bitmap -> stream -> Bitmap use bitap from Intent to save image.

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
    {
        if (resultCode == Activity.RESULT_OK)
        {
            Bitmap bmp = (Bitmap)data.getExtras().get("data");
            imageView.setImageBitmap(bmp);

            // here try to inovke saveImageMethod
        }
    }
}

public void saveImage(Bitmap bmp, String filename)
{
    FileOutputStream out = null;
    try {
        out = new FileOutputStream(filename);
        bmp.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

But remember about asking external storage permission. And if you wish to share this File you must use FileProvider api. For more info check https://developer.android.com/training/basics/data-storage/files.html

bongo
  • 733
  • 4
  • 12
0

You can save your image in internal storage using below code

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
{
    if (resultCode == Activity.RESULT_OK)
    {
        Bitmap bmp = (Bitmap)data.getExtras().get("data");
        ByteArrayOutputStream stream = new ByteArrayOutputStream();

        bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
        byte[] byteArray = stream.toByteArray();

        //saving image into internal storage

        File myfile = new File(Environment.getExternalStorageDirectory(),"yourfilename.jpg");

        FileOutputStream fo;
        try {
            myfile.createNewFile();
            fo = new FileOutputStream(myfile);
            fo.write(byteArray);
            fo.flush();
            fo.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // convert byte array to Bitmap

        Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0,
                byteArray.length);

        imageView.setImageBitmap(bitmap);

    }
  }
}
DB377
  • 403
  • 4
  • 11