SoFunction
Updated on 2025-04-09

Android realizes the functions of taking photos, selecting albums and cropping

Get the picture by taking photos or albums, and cropping it, and then display the picture on the ImageView.
Of course, it can also be uploaded to the server (most of the cases in the project are uploaded to the server), refer to online information and combined with the actual situation of the project,
There are no serious problems found after testing many mobile phones. The code has comments, just paste the code:

public class UploadPicActivity extends Activity implements  {
 private Button take_photo_btn;
 private Button select_photo_btn;
 private ImageView photo_iv;
 //Use the camera to take pictures to get pictures public static final int TAKE_PHOTO_CODE = 1;
 //Use pictures in the album public static final int SELECT_PIC_CODE = 2;
 //Picture cropping private static final int PHOTO_CROP_CODE = 3;
 //Define the Uri of the picture private Uri photoUri;
 //Picture file path private String picPath;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  (savedInstanceState);
  setContentView(.activity_upload_pic);
  initViews();
 }

 private void initViews() {
  this.take_photo_btn = (Button) findViewById(.take_photo_btn);
  this.take_photo_btn.setOnClickListener(this);
  this.select_photo_btn = (Button) findViewById(.select_photo_btn);
  this.select_photo_btn.setOnClickListener(this);
  this.photo_iv = (ImageView) findViewById(.photo_iv);
 }

 @Override
 public void onClick(View view) {
  switch (()) {
   //Photograph   case .take_photo_btn:
    picTyTakePhoto();
    break;
   //Select a gallery   case .select_photo_btn:
    pickPhoto();
    break;
  }
 }

 /**
   * Take a photo to get pictures
   */
 private void picTyTakePhoto() {
  //Judge whether the SD card exists  String SDState = ();
  if ((Environment.MEDIA_MOUNTED)) {
   Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//".IMAGE_CAPTURE"
/***
  * Use the camera to take pictures, and the pictures after taking pictures will be stored in the album.  The advantage of using this method is that the image obtained is the original image after taking a photo.
  * If ContentValues ​​is not practical to store the photo path, the picture obtained after taking a photo may be unclear.
  */
   ContentValues values = new ContentValues();
   photoUri = getContentResolver().insert(.EXTERNAL_CONTENT_URI, values);
   (.EXTRA_OUTPUT, photoUri);
   startActivityForResult(intent, TAKE_PHOTO_CODE);
  } else {
   (this, "The memory card does not exist", Toast.LENGTH_LONG).show();
  }
 }

 /***
   * Get pictures from the album
   */
 private void pickPhoto() {
  Intent intent = new Intent(Intent.ACTION_PICK, null);
  (.EXTERNAL_CONTENT_URI,
    "image/*");
   startActivityForResult(intent, SELECT_PIC_CODE);
  }

  @Override
  public void onActivityResult(int requestCode, int resultCode, Intent data) {
   (requestCode, resultCode, data);
   if (resultCode == Activity.RESULT_OK) {
    //Pick up pictures from the album. Some mobile phones have abnormalities. Please pay attention.
    if (requestCode == SELECT_PIC_CODE) {
     if (null != data && null != ()) {
      photoUri = ();
      picPath = uriToFilePath(photoUri);
      startPhotoZoom(photoUri, PHOTO_CROP_CODE);
     } else {
      (this, "Image selection failed", Toast.LENGTH_LONG).show();
     }
    } else if (requestCode == TAKE_PHOTO_CODE) {
     String[] pojo = {};
     Cursor cursor = managedQuery(photoUri, pojo, null, null, null);
     if (cursor != null) {
      int columnIndex = (pojo[0]);
      ();
      picPath = (columnIndex);
      if (.SDK_INT < 14) {
       ();
      }
     }
     if (picPath != null) {
      photoUri = (new File(picPath));
      startPhotoZoom(photoUri, PHOTO_CROP_CODE);
     } else {
      (this, "Image selection failed", Toast.LENGTH_LONG).show();
     }
    } else if (requestCode == PHOTO_CROP_CODE) {
     if (photoUri != null) {
      Bitmap bitmap = (picPath);
      if (bitmap != null) {
       // Here you can upload the image to the server
       photo_iv.setImageBitmap(bitmap);
      }
     }
    }
   }
  }

  /**
   * @param
   * @description Crop the picture
   * @author ldm
   * @time 2016/11/30 15:19
   */
 private void startPhotoZoom(Uri uri, int REQUE_CODE_CROP) {
  Intent intent = new Intent("");
  (uri, "image/*");
   // crop=true is the VIEW clipping that is set to be displayed in the enabled Intent
   ("crop", "true");
   // Get rid of black border
   ("scale", true);
   ("scaleUpIfNeeded", true);
   // aspectX aspectY is the ratio of width and height, and be modified according to your own situation
   ("aspectX", 3);
   ("aspectY", 2);
   // outputX outputY is the width and height pixel of the cropped image
   ("outputX", 600);
   ("outputY", 400);
   ("outputFormat", ());
   //Cancel face recognition function
   ("noFaceDetection", true);
   //Set the returned uri
   (MediaStore.EXTRA_OUTPUT, uri);
   //Set to not return data
   ("return-data", false);
   startActivityForResult(intent, REQUE_CODE_CROP);
  }

  /**
   * @param
   * @description Convert Uri to file path
   * @author ldm
   * @time 2016/11/30 15:22
   */
 private String uriToFilePath(Uri uri) {
  //Get picture data  String[] proj = {};
  //Inquiry  Cursor cursor = managedQuery(uri, proj, null, null, null);
  //Get the index value of the image selected by the user  int image_index = ();
  ();
  //Return to the image path  return (image_index);
 }
}

The layout file looks like this:

&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;LinearLayout xmlns:andro
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp"&gt;

 &lt;Button
  android:
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_marginTop="20dp"
  android:gravity="center"
  android:text="Photograph"
  android:textSize="16sp"/&gt;

 &lt;Button
  android:
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_marginTop="20dp"
  android:gravity="center"
  android:text="Select Picture"
  android:textSize="16sp"/&gt;

 &lt;ImageView
  android:
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_gravity="center_horizontal"
  android:layout_marginTop="20dp"/&gt;
&lt;/LinearLayout&gt;

Finally, don't forget to add UploadPicActivity and permissions:

<uses-permission android:name=""/>
<uses-permission android:name=".WRITE_EXTERNAL_STORAGE"/>
<uses-permission 
 android:name=".MOUNT_UNMOUNT_FILESYSTEMS"/>

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.