How can i take a picture with custom camera and display it on another activity?

1.3k views Asked by At

Please help me how to take a picture from a custom camera and display it on another activity, please give me more detailed answer, what code should i put, and where, please tell me if what kind of variables, int, strings, booleans should i create,
here is my code :

Main Activity :

1

There are 1 answers

10
Emma On BEST ANSWER
@Override
public void onPictureTaken(byte[] data, Camera camera) {
    final Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);

    // Store bitmap to local storage
    FileOutputStream out = null;
    try {
        // Prepare file path to store bitmap
        // This will create Pictures/MY_APP_NAME_DIR/
        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES), "MY_APP_NAME_DIR");
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d(Constants.LOG_TAG, "failed to create directory");
                return null;
            }
        }

        // Bitmap will be stored at /Pictures/MY_APP_NAME_DIR/YOUR_FILE_NAME.jpg
        String filePath = mediaStorageDir.getPath() + File.separator + "YOUR_FILE_NAME.jpg";
        out = new FileOutputStream(filePath);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out); 
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

You can use interface to pass YOUR_FILE_PATH from CameraPreview class to MainActivity class. then in MainActivity.java

Intent i = new Intent(this, EditPicture.class);
i.putExtra("FILE_PATH", YOUR_FILE_PATH);
startActivity(i);

in EditPicture activity

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (getIntent().hasExtra("FILE_PATH")) {
        String filePath = getIntent().getStringExtra("FILE_PATH");

        // Read bitmap from local file
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
        yourImageView.setImageBitmap(bitmap);
    }
}

Finally, add <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> to your AndroidManifest.xml in order to allow your app writing to external storage.

This is the example of how to write bitmap to external storage. If you want to store to internal storage such as cache or other options, please refer to http://developer.android.com/guide/topics/data/data-storage.html#filesInternal

Let me know if you need me to elaborate more.