demo

Let’s start with a simple demo of android photography

XML code

    <Button
        android:id="@+id/take_photo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Take Photo"/>

    <ImageView
        android:id="@+id/picture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"/>
Copy the code

A Button and an ImageView. A Button is used to turn on the camera to take a picture, and an ImageView is used to display the image taken

Java code

import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.ImageView; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; public class MainActivity extends AppCompatActivity implements View.OnClickListener { public static final int TAKE_PHOTO = 1; public static final int CROP_PHOTO = 2; private Button takePhoto; private ImageView picture; private Uri imageUri; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); takePhoto = (Button) findViewById(R.id.take_photo); picture = (ImageView) findViewById(R.id.picture); takePhoto.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.take_photo: File outputImage = new File(Environment.getExternalStorageDirectory(), "tempImage" + ".jpg"); try { if (outputImage.exists()) { outputImage.delete(); } outputImage.createNewFile(); } catch (IOException e) { e.printStackTrace(); } imageUri = Uri.fromFile(outputImage); Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); startActivityForResult(intent, TAKE_PHOTO); break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case TAKE_PHOTO: if (resultCode == RESULT_OK) { Intent intent = new Intent("com.android.camera.action.CROP"); intent.setDataAndType(imageUri, "image/*"); intent.putExtra("scale", true); intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); startActivityForResult(intent, CROP_PHOTO); } break; case CROP_PHOTO: if (resultCode == RESULT_OK) { try { Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver() .openInputStream(imageUri)); picture.setImageBitmap(bitmap); } catch (FileNotFoundException e) { e.printStackTrace(); } } break; }}}Copy the code

Add click event to button button to call camera

1. Create a File object to store the image captured by the camera. Here we call the image tempimage.jpg and store it in the root directory of our mobile SD card. Tone with the Environment external.getexternalstoragedirectory () access to the mobile phone is the root directory of the SD card 2, and then call the Uri fromFile () method to convert the File object to a Uri object, Create an Intent object and specify the action as Android.media.action.image_capture. Call the putExtra() method of the Intent to specify the output address of the image, fill in the Uri object, and start the activity by calling startActivityForResult(). The system launches an activity that responds to the Intent, so the camera program is opened and the photo captured is output to tempImage.jpg. So the result is returned to the onActivityResult() method after the photo is taken. Found that photo 6, if successful, will construct an Intent object again, and put it in the action specified for the com. Android. Camera. The action. The CROP, the Intent is to take the photos for tailoring, because the camera pictures are big, We might just want to intercept a small portion of the Intent, set the necessary properties to the Intent, and call startActivityForResult() again to start the clipper. The clipped image is also output to tempimage.jpg. 7. Once the clipping operation is complete, the program is called back to onActivityResult(). At this point we can call the BitmapFactory decodeStream() method to parse the output_image.jpg image into a Bitmap and then set it to display in the ImageView

AndroidManifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Copy the code

Since this project involves writing data to an SD card, we also need to declare permissions in androidmanifest.xml

Modified for 7.0

An update to the permissions of Android 7.0 disallowed implicit APP calls in the format of file:// and required shared file: content:// URI

The rest of the code remains the same, but the Java code has been modified as follows

import android.Manifest; import android.app.Activity; import android.content.ContentValues; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; import java.io.File; import java.io.FileNotFoundException; import java.text.SimpleDateFormat; import java.util.Date; public class MainActivity extends AppCompatActivity implements View.OnClickListener { public static final int PHOTO_REQUEST_CAREMA = 1; Public static final int CROP_PHOTO = 2; private Button takePhoto; private ImageView picture; private Uri imageUri; public static File tempFile; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); takePhoto = (Button) findViewById(R.id.take_photo); picture = (ImageView) findViewById(R.id.picture); takePhoto.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.take_photo: openCamera(this); break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case PHOTO_REQUEST_CAREMA: if (resultCode == RESULT_OK) { Intent intent = new Intent("com.android.camera.action.CROP"); intent.setDataAndType(imageUri, "image/*"); intent.putExtra("scale", true); intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); startActivityForResult(intent, CROP_PHOTO); } break; case CROP_PHOTO: if (resultCode == RESULT_OK) { try { Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver() .openInputStream(imageUri)); picture.setImageBitmap(bitmap); } catch (FileNotFoundException e) { e.printStackTrace(); } } break; }} public void openCamera (Activity Activity) {/ / acquisition system VERSION int currentapiVersion. = android OS. Build. VERSION. SDK_INT; Intent Intent = new Intent(mediastore.action_image_capture); // Check whether the memory card is usable. If (hasSdcard()) {SimpleDateFormat timeStampFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss"); String filename = timeStampFormat.format(new Date()); tempFile = new File(Environment.getExternalStorageDirectory(), filename + ".jpg"); If (currentapiVersion < 24) {imageUri = uri.fromFile (tempFile); intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); } else {// Compatible android7.0 use shared file form ContentValues ContentValues = new ContentValues(1); contentValues.put(MediaStore.Images.Media.DATA, tempFile.getAbsolutePath()); / / check if there is a store permissions, in order to avoid collapse if (ContextCompat. CheckSelfPermission (this, the Manifest. Permission. WRITE_EXTERNAL_STORAGE)! = PackageManager. PERMISSION_GRANTED) {/ / WRITE_EXTERNAL_STORAGE permission application Toast.maketext (this," please open storage permissions ", toast.length_short).show(); return; } imageUri = activity.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues); intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); }} / / open with a return value of the Activity, the request code for PHOTO_REQUEST_CAREMA Activity. StartActivityForResult (intent, PHOTO_REQUEST_CAREMA); } / * * determine whether sdcard is mounted * / public static Boolean hasSdcard () {return Environment. GetExternalStorageState () equals ( Environment.MEDIA_MOUNTED); }}Copy the code

* It should be noted that the app installed on the mobile phone needs to check whether the storage permission is enabled

The effect is as follows:

Retrieve the system album

What if we want to select an image from the system’s album?

Take a look at the renderings first

Add an openGallery() method

public void openGallery() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, CROP_PHOTO);
    }
Copy the code

Change the button click event to

@Override public void onClick(View v) { switch (v.getId()) { case R.id.take_photo: //openCamera(this); openGallery(); break; }}Copy the code

Because the request code here is CROP_PHOTO, I’m going to change CROP_PHOTO up here

 @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case TAKE_PHOTO:
                ...
                break;
            case CROP_PHOTO:
                if (resultCode == RESULT_OK) {
                    try {
                        if(data != null) {
                            Uri uri = data.getData();
                            imageUri = uri;
                        }
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver()
                                .openInputStream(imageUri));
                        picture.setImageBitmap(bitmap);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                break;
            default:
                super.onActivityResult(requestCode, resultCode, data);
                break;
        }
    }
Copy the code

Demo source download

Download.csdn.net/download/u0…