How to move image captured with the phone camera from one activity to an image view in another activity?

后端 未结 3 1110

The first activity has a button which when clicked, opens the inbuilt camera. Now when the picture is taken, a new activity opens with the image captured in an imageVi

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-21 09:03

    Here are my solution, I have tested in my environment. Hope this helps!

    If using emulator to test, make sure camera supported like this

    UPDATE WIH FULL SOURCE CODE (NEW PROJECT):

    MainActivity.java:

    package com.example.photocapture;
    
    import android.app.Activity;
    import android.content.Context;
    import android.content.Intent;
    import android.net.Uri;
    import android.os.Bundle;
    import android.os.Environment;
    import android.provider.MediaStore;
    import android.view.Menu;
    import android.view.MenuItem;
    
    import java.io.File;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Locale;
    
    public class MainActivity extends Activity {
    
        private Uri mFileUri;
        private final Context mContext = this;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    
            mFileUri = getOutputMediaFileUri(1);
    
            intent.putExtra(MediaStore.EXTRA_OUTPUT, mFileUri);
    
            // start the image capture Intent
            startActivityForResult(intent, 100);
        }
    
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
            super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
    
            if (resultCode == RESULT_OK) {
                if (mFileUri != null) {
                    String mFilePath = mFileUri.toString();
                    if (mFilePath != null) {
                        Intent intent = new Intent(mContext, SecondActivity.class);
                        intent.putExtra("filepath", mFilePath);
                        startActivity(intent);
                    }
                }
            }               
        }
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.menu_main, menu);
            return true;
        }
    
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();
    
            //noinspection SimplifiableIfStatement
            if (id == R.id.action_settings) {
                return true;
            }
    
            return super.onOptionsItemSelected(item);
        }
    
        private Uri getOutputMediaFileUri(int type) {
            return Uri.fromFile(getOutputMediaFile(type));
        }
    
        // Return image / video
        private static File getOutputMediaFile(int type) {
    
            // External sdcard location
            File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), "DCIM/Camera");
    
            // Create the storage directory if it does not exist
            if (!mediaStorageDir.exists()) {
                if (!mediaStorageDir.mkdirs()) {
                    return null;
                }
            }
    
            // Create a media file name
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
            File mediaFile;
            if (type == 1) { // image
                mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
            } else if (type == 2) { // video
                mediaFile = new File(mediaStorageDir.getPath() + File.separator + "VID_" + timeStamp + ".mp4");
            } else {
                return null;
            }
    
            return mediaFile;
        }
    }
    

    SecondActivity.java:

    package com.example.photocapture;
    
    import android.app.Activity;
    import android.content.Intent;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.widget.ImageView;
    
    import java.io.File;
    
    public class SecondActivity extends Activity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_second);
    
            Intent intent = getIntent();
            String filepath = intent.getStringExtra("filepath");
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 8; // down sizing image as it throws OutOfMemory Exception for larger images
            filepath = filepath.replace("file://", ""); // remove to avoid BitmapFactory.decodeFile return null
            File imgFile = new File(filepath);
            if (imgFile.exists()) {
                ImageView imageView = (ImageView) findViewById(R.id.imageView);
                Bitmap bitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath(), options);
                imageView.setImageBitmap(bitmap);
            }
        }
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.menu_second, menu);
            return true;
        }
    
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();
    
            //noinspection SimplifiableIfStatement
            if (id == R.id.action_settings) {
                return true;
            }
    
            return super.onOptionsItemSelected(item);
        }
    }
    

    activity_main.xml:

    
    
        
    
    
    

    activity_second.xml:

    
    
        
    
    
    

    AndroidManifest.xml:

    
    
    
        
            
                
                    
    
                    
                
            
            
            
        
    
    
    

    END OF NEW PROJECT

    ------------------

    FirstActivity:

        private final Context mContext = this;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.activity_first);
    
           buttonCapturePicture.setOnClickListener(new View.OnClickListener() {
    
               @Override
               public void onClick(View v) {                   
                   captureImage();
               }
            });
        }
    
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
            super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
    
            if (resultCode == RESULT_OK) {
                if (mFileUri != null) {
                    mFilePath = mFileUri.toString();
                    if (mFilePath != null) {                    
                        Intent intent = new Intent(mContext, SecondActivity.class);
                        intent.putExtra("filepath", mFilePath);
                        startActivity(intent);
                    }
                }
            }
    
            // refresh phone's folder content
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
        }
    
        private void captureImage() {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    
            mFileUri = getOutputMediaFileUri(1);
    
            intent.putExtra(MediaStore.EXTRA_OUTPUT, mFileUri);
    
            // start the image capture Intent
            startActivityForResult(intent, 100);
        }
    
    
        private Uri getOutputMediaFileUri(int type) {
            return Uri.fromFile(getOutputMediaFile(type));
        }
    
        private static File getOutputMediaFile(int type) {
            // External sdcard location
            File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), "DCIM/Camera");
    
            // Create the storage directory if it does not exist
            if (!mediaStorageDir.exists()) {
                if (!mediaStorageDir.mkdirs()) {
                    return null;
                }
            }
    
            // Create a media file name
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
            File mediaFile;
            if (type == 1) {
                mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
            } else if (type == 2) {
                mediaFile = new File(mediaStorageDir.getPath() + File.separator + "VID_" + timeStamp + ".mp4");
            } else {
                return null;
            }
    
            return mediaFile;
        }
    

    SecondActivity:

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            super.addContentView(R.layout.activity_second);
    
            Intent intent = getIntent();
            mFilePath = intent.getStringExtra("filepath");
            previewMedia();
            ...
        }
    
        private void previewMedia() {              
                BitmapFactory.Options options = new BitmapFactory.Options();            
                options.inSampleSize = 8; // down sizing image as it throws OutOfMemory Exception for larger images
                mFilePath = mFilePath.replace("file://", ""); // remove to avoid BitmapFactory.decodeFile return null
                File imgFile = new File(mFilePath);
                if (imgFile.exists()) {
                    final Bitmap bitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath(), options);
                    mImagePreview.setImageBitmap(bitmap);
                }
            }
    

提交回复
热议问题