Capture Image from Camera and Display in Activity

前端 未结 16 1036
悲&欢浪女
悲&欢浪女 2020-11-21 06:43

I want to write a module where on a click of a button the camera opens and I can click and capture an image. If I don\'t like the image I can delete it and click one more i

相关标签:
16条回答
  • 2020-11-21 06:58

    Capture photo from camera + pick image from gallery and set it into the background of layout or imageview. Here is sample code.

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    
    import android.app.Activity;
    import android.app.AlertDialog;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.database.Cursor;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.graphics.drawable.BitmapDrawable;
    import android.graphics.drawable.Drawable;
    import android.net.Uri;
    import android.os.Bundle;
    import android.os.Environment;
    
        import android.provider.MediaStore;
        import android.util.Log;
        import android.view.View;
        import android.view.View.OnClickListener;
        import android.widget.AdapterView;
        import android.widget.AdapterView.OnItemClickListener;
        import android.widget.GridView;
        import android.widget.ImageView;
        import android.widget.LinearLayout;
    
        public class Post_activity extends Activity
        {
            final int TAKE_PICTURE = 1;
            final int ACTIVITY_SELECT_IMAGE = 2;
    
            ImageView openCameraOrGalleryBtn,cancelBtn;
            LinearLayout backGroundImageLinearLayout;
    
            public void onCreate(Bundle savedBundleInstance) {
                super.onCreate(savedBundleInstance);
                overridePendingTransition(R.anim.slide_up,0);
                setContentView(R.layout.post_activity);
    
                backGroundImageLinearLayout=(LinearLayout)findViewById(R.id.background_image_linear_layout);
                cancelBtn=(ImageView)findViewById(R.id.cancel_icon);
    
                openCameraOrGalleryBtn=(ImageView)findViewById(R.id.camera_icon);
    
    
    
                openCameraOrGalleryBtn.setOnClickListener(new OnClickListener() {
    
                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
    
                        selectImage();
                    }
                });
                cancelBtn.setOnClickListener(new OnClickListener() {
    
                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                    overridePendingTransition(R.anim.slide_down,0);
                    finish();
                    }
                });
    
            }
    
        public void selectImage()
            {
                 final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
                 AlertDialog.Builder builder = new AlertDialog.Builder(Post_activity.this);
                    builder.setTitle("Add Photo!");
                    builder.setItems(options,new DialogInterface.OnClickListener() {
    
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // TODO Auto-generated method stub
                            if(options[which].equals("Take Photo"))
                            {
                                Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
                                startActivityForResult(cameraIntent, TAKE_PICTURE);
                            }
                            else if(options[which].equals("Choose from Gallery"))
                            {
                                Intent intent=new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                                startActivityForResult(intent, ACTIVITY_SELECT_IMAGE);
                            }
                            else if(options[which].equals("Cancel"))
                            {
                                dialog.dismiss();
                            }
    
                        }
                    });
                    builder.show();
            }
            public void onActivityResult(int requestcode,int resultcode,Intent intent)
            {
                super.onActivityResult(requestcode, resultcode, intent);
                if(resultcode==RESULT_OK)
                {
                    if(requestcode==TAKE_PICTURE)
                    {
                        Bitmap photo = (Bitmap)intent.getExtras().get("data"); 
                        Drawable drawable=new BitmapDrawable(photo);
                        backGroundImageLinearLayout.setBackgroundDrawable(drawable);
    
                    }
                    else if(requestcode==ACTIVITY_SELECT_IMAGE)
                    {
                        Uri selectedImage = intent.getData();
                        String[] filePath = { MediaStore.Images.Media.DATA };
                        Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
                        c.moveToFirst();
                        int columnIndex = c.getColumnIndex(filePath[0]);
                        String picturePath = c.getString(columnIndex);
                        c.close();
                        Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
                        Drawable drawable=new BitmapDrawable(thumbnail);
                        backGroundImageLinearLayout.setBackgroundDrawable(drawable);
    
    
                    }
                }
            }
    
            public void onBackPressed() {
                super.onBackPressed();
                //overridePendingTransition(R.anim.slide_down,0);
            }
        }
    
    Add these permission in Androidmenifest.xml file
    
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
        <uses-permission android:name="android.permission.CAMERA"/>
    
    0 讨论(0)
  • 2020-11-21 06:59

    Here's an example activity that will launch the camera app and then retrieve the image and display it.

    package edu.gvsu.cis.masl.camerademo;
    
    import android.app.Activity;
    import android.content.Intent;
    import android.graphics.Bitmap;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.ImageView;
    
    public class MyCameraActivity extends Activity
    {
        private static final int CAMERA_REQUEST = 1888; 
        private ImageView imageView;
        private static final int MY_CAMERA_PERMISSION_CODE = 100;
    
        @Override
        public void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            this.imageView = (ImageView)this.findViewById(R.id.imageView1);
            Button photoButton = (Button) this.findViewById(R.id.button1);
            photoButton.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
                    {
                        requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_CAMERA_PERMISSION_CODE);
                    }
                    else
                    {
                        Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
                        startActivityForResult(cameraIntent, CAMERA_REQUEST);
                    } 
                }
            });
        }
    
        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
        {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            if (requestCode == MY_CAMERA_PERMISSION_CODE)
            {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
                {
                    Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();
                    Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
                    startActivityForResult(cameraIntent, CAMERA_REQUEST);
                }
                else
                {
                    Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();
                }
            }
        }
    
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data)
        {  
            if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK)
            {  
                Bitmap photo = (Bitmap) data.getExtras().get("data"); 
                imageView.setImageBitmap(photo);
            }  
        } 
    }
    

    Note that the camera app itself gives you the ability to review/retake the image, and once an image is accepted, the activity displays it.

    Here is the layout that the above activity uses. It is simply a LinearLayout containing a Button with id button1 and an ImageView with id imageview1:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        >
        <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/photo"></Button>
        <ImageView android:id="@+id/imageView1" android:layout_height="wrap_content" android:src="@drawable/icon" android:layout_width="wrap_content"></ImageView>
    
    </LinearLayout>
    

    And one final detail, be sure to add:

    <uses-feature android:name="android.hardware.camera"></uses-feature> 
    

    and if camera is optional to your app functionality. make sure to set require to false in the permission. like this

    <uses-feature android:name="android.hardware.camera" android:required="false"></uses-feature>
    

    to your manifest.xml.

    0 讨论(0)
  • 2020-11-21 07:01

    Here is code I have used for Capturing and Saving Camera Image then display it to imageview. You can use according to your need.

    You have to save Camera image to specific location then fetch from that location then convert it to byte-array.

    Here is method for opening capturing camera image activity.

    private static final int CAMERA_PHOTO = 111;
    private Uri imageToUploadUri;
    
    private void captureCameraImage() {
            Intent chooserIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            File f = new File(Environment.getExternalStorageDirectory(), "POST_IMAGE.jpg");
            chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
            imageToUploadUri = Uri.fromFile(f);
            startActivityForResult(chooserIntent, CAMERA_PHOTO);
        }
    

    then your onActivityResult() method should be like this.

    @Override
            protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                super.onActivityResult(requestCode, resultCode, data);
    
                if (requestCode == CAMERA_PHOTO && resultCode == Activity.RESULT_OK) {
                    if(imageToUploadUri != null){
                        Uri selectedImage = imageToUploadUri;
                        getContentResolver().notifyChange(selectedImage, null);
                        Bitmap reducedSizeBitmap = getBitmap(imageToUploadUri.getPath());
                        if(reducedSizeBitmap != null){
                            ImgPhoto.setImageBitmap(reducedSizeBitmap);
                            Button uploadImageButton = (Button) findViewById(R.id.uploadUserImageButton);
                              uploadImageButton.setVisibility(View.VISIBLE);                
                        }else{
                            Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
                        }
                    }else{
                        Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
                    }
                } 
            }
    

    Here is getBitmap() method used in onActivityResult(). I have done all performance improvement that can be possible while getting camera capture image bitmap.

    private Bitmap getBitmap(String path) {
    
            Uri uri = Uri.fromFile(new File(path));
            InputStream in = null;
            try {
                final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
                in = getContentResolver().openInputStream(uri);
    
                // Decode image size
                BitmapFactory.Options o = new BitmapFactory.Options();
                o.inJustDecodeBounds = true;
                BitmapFactory.decodeStream(in, null, o);
                in.close();
    
    
                int scale = 1;
                while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) >
                        IMAGE_MAX_SIZE) {
                    scale++;
                }
                Log.d("", "scale = " + scale + ", orig-width: " + o.outWidth + ", orig-height: " + o.outHeight);
    
                Bitmap b = null;
                in = getContentResolver().openInputStream(uri);
                if (scale > 1) {
                    scale--;
                    // scale to max possible inSampleSize that still yields an image
                    // larger than target
                    o = new BitmapFactory.Options();
                    o.inSampleSize = scale;
                    b = BitmapFactory.decodeStream(in, null, o);
    
                    // resize to desired dimensions
                    int height = b.getHeight();
                    int width = b.getWidth();
                    Log.d("", "1th scale operation dimenions - width: " + width + ", height: " + height);
    
                    double y = Math.sqrt(IMAGE_MAX_SIZE
                            / (((double) width) / height));
                    double x = (y / height) * width;
    
                    Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x,
                            (int) y, true);
                    b.recycle();
                    b = scaledBitmap;
    
                    System.gc();
                } else {
                    b = BitmapFactory.decodeStream(in);
                }
                in.close();
    
                Log.d("", "bitmap size - width: " + b.getWidth() + ", height: " +
                        b.getHeight());
                return b;
            } catch (IOException e) {
                Log.e("", e.getMessage(), e);
                return null;
            }
        }
    

    Hope it helps!

    0 讨论(0)
  • 2020-11-21 07:03

    You can use custom camera with thumbnail image. You can look my project.

    0 讨论(0)
  • 2020-11-21 07:05

    You can use this code to onClick listener (you can use ImageView or button)

    image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                    startActivityForResult(takePictureIntent, 1);
                }
            }
        });
    

    To display in your imageView

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            Bundle extras = data.getExtras();
            bitmap = (Bitmap) extras.get("data");
            image.setImageBitmap(bitmap);
    
        }
    }
    

    Note: Insert this to the manifest

    <uses-feature android:name="android.hardware.camera" android:required="true" />
    
    0 讨论(0)
  • 2020-11-21 07:06

    Here you can open camera or gallery and set the selected image into imageview

    private static final String IMAGE_DIRECTORY = "/YourDirectName";
    private Context mContext;
    private CircleImageView circleImageView;  // imageview
    private int GALLERY = 1, CAMERA = 2;
    

    Add permissions in manifest

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

    In onCreate()

        requestMultiplePermissions(); // check permission 
    
        circleImageView = findViewById(R.id.profile_image);
        circleImageView.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showPictureDialog();
            }
        });
    

    Show options dialog box (to select image from camera or gallery)

    private void showPictureDialog() {
        AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
        pictureDialog.setTitle("Select Action");
        String[] pictureDialogItems = {"Select photo from gallery", "Capture photo from camera"};
        pictureDialog.setItems(pictureDialogItems,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0:
                                choosePhotoFromGallary();
                                break;
                            case 1:
                                takePhotoFromCamera();
                                break;
                        }
                    }
                });
        pictureDialog.show();
    }
    

    Get photo from Gallery

    public void choosePhotoFromGallary() {
        Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(galleryIntent, GALLERY);
    }
    

    Get photo from Camera

    private void takePhotoFromCamera() {
        Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, CAMERA);
    }
    

    Once the image is get selected or captured then ,

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == this.RESULT_CANCELED) {
            return;
        }
        if (requestCode == GALLERY) {
            if (data != null) {
                Uri contentURI = data.getData();
                try {
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), contentURI);
                    String path = saveImage(bitmap);
                    Toast.makeText(getApplicationContext(), "Image Saved!", Toast.LENGTH_SHORT).show();
                    circleImageView.setImageBitmap(bitmap);
    
                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Failed!", Toast.LENGTH_SHORT).show();
                }
            }
    
        } else if (requestCode == CAMERA) {
            Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
            circleImageView.setImageBitmap(thumbnail);
            saveImage(thumbnail);
            Toast.makeText(getApplicationContext(), "Image Saved!", Toast.LENGTH_SHORT).show();
        }
    }
    

    Now its time to store the picture

    public String saveImage(Bitmap myBitmap) {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
        File wallpaperDirectory = new File(Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
        if (!wallpaperDirectory.exists()) {  // have the object build the directory structure, if needed.
            wallpaperDirectory.mkdirs();
        }
    
        try {
            File f = new File(wallpaperDirectory, Calendar.getInstance().getTimeInMillis() + ".jpg");
            f.createNewFile();
            FileOutputStream fo = new FileOutputStream(f);
            fo.write(bytes.toByteArray());
            MediaScannerConnection.scanFile(this,
                    new String[]{f.getPath()},
                    new String[]{"image/jpeg"}, null);
            fo.close();
            Log.d("TAG", "File Saved::---&gt;" + f.getAbsolutePath());
    
            return f.getAbsolutePath();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return "";
    }
    

    Request permission

        private void requestMultiplePermissions() {
        Dexter.withActivity(this)
                .withPermissions(
                        Manifest.permission.CAMERA,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE)
                .withListener(new MultiplePermissionsListener() {
                    @Override
                    public void onPermissionsChecked(MultiplePermissionsReport report) {
                        if (report.areAllPermissionsGranted()) {  // check if all permissions are granted
                            Toast.makeText(getApplicationContext(), "All permissions are granted by user!", Toast.LENGTH_SHORT).show();
                        }
    
                        if (report.isAnyPermissionPermanentlyDenied()) { // check for permanent denial of any permission
                            // show alert dialog navigating to Settings
                            //openSettingsDialog();
                        }
                    }
    
                    @Override
                    public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
                        token.continuePermissionRequest();
                    }
                }).
                withErrorListener(new PermissionRequestErrorListener() {
                    @Override
                    public void onError(DexterError error) {
                        Toast.makeText(getApplicationContext(), "Some Error! ", Toast.LENGTH_SHORT).show();
                    }
                })
                .onSameThread()
                .check();
    }
    
    0 讨论(0)
提交回复
热议问题