简体   繁体   English

通过用户从图库中选择图像来裁剪图像

[英]Cropping Image by user selecting image from gallery

I am creating an application in android in which I want to let the user select his profile pic from a photo gallery. 我正在android中创建一个应用程序,我想让用户从相册中选择他的个人资料照片。 I want to let the user crop an image for his profile picture when selecting the image from the gallery, or capturing an image from the camera. 我想让用户在从图库中选择图像或从相机捕获图像时,为自己的个人头像裁剪图像。 I am using the image chooser library for capturing or choosing an image from library. 我正在使用图像选择器库来捕获图像或从库中选择图像。 Can anyone suggest what would be the best way to implement this? 谁能建议实现此目标的最佳方法是什么?

First You can use this code to take image from galley and with camera : It Surely works: 首先,您可以使用此代码从厨房和相机拍摄图像:它确实可以工作:

        private void selectImage() {
    final CharSequence[] items = { "Take Photo", "Choose from Library", "Cancel" };
    AlertDialog.Builder builder = new AlertDialog.Builder(Enrolement.this);
    builder.setTitle("Add Photo!");
    builder.setItems(items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int item) {
            if (items[item].equals("Take Photo")) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, REQUEST_CAMERA);
            } else if (items[item].equals("Choose from Library")) {
                Intent intent = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                intent.setType("image/*");
                startActivityForResult(
                        Intent.createChooser(intent, "Select File"),
                        SELECT_FILE);
            } else if (items[item].equals("Cancel")) {
                dialog.dismiss();
            }
        }
    });
    builder.show();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == Activity.RESULT_OK) {
        if (requestCode == SELECT_FILE)
            onSelectFromGalleryResult(data);
        else if (requestCode == REQUEST_CAMERA)
            onCaptureImageResult(data);
    }
}

private void onCaptureImageResult(Intent data) {
    Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);

    File destination = new File(Environment.getExternalStorageDirectory(),
            System.currentTimeMillis() + ".jpg");

    FileOutputStream fo;
    try {
        destination.createNewFile();
        fo = new FileOutputStream(destination);
        fo.write(bytes.toByteArray());
        fo.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    ivImage.setImageBitmap(thumbnail);
}

@SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
    Uri selectedImageUri = data.getData();
    String[] projection = { MediaStore.MediaColumns.DATA };
    Cursor cursor = managedQuery(selectedImageUri, projection, null, null,
            null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
    cursor.moveToFirst();

    String selectedImagePath = cursor.getString(column_index);

    Bitmap bm;
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(selectedImagePath, options);
    final int REQUIRED_SIZE = 200;
    int scale = 1;
    while (options.outWidth / scale / 2 >= REQUIRED_SIZE
            && options.outHeight / scale / 2 >= REQUIRED_SIZE)
        scale *= 2;
    options.inSampleSize = scale;
    options.inJustDecodeBounds = false;
    bm = BitmapFactory.decodeFile(selectedImagePath, options);

    ivImage.setImageBitmap(bm);
} 

Main Part is cropping : U can call startActivity() on an Intent with an action of com.android.camera.action.CROP 主要部分是裁剪:U可以使用com.android.camera.action.CROP操作在Intent上调用startActivity()

       Intent intent = new Intent("com.android.camera.action.CROP");  
  intent.setClassName("com.android.camera", "com.android.camera.CropImage");  
 File file = new File(filePath);  
 Uri uri = Uri.fromFile(file);  
intent.setData(uri);  
intent.putExtra("crop", "true");  
 intent.putExtra("aspectX", 1);  
intent.putExtra("aspectY", 1);  
intent.putExtra("outputX", 96);  
 intent.putExtra("outputY", 96);  
  intent.putExtra("noFaceDetection", true);  
 intent.putExtra("return-data", true);                                  
 startActivityForResult(intent, REQUEST_CROP_ICON);

When the picture select Activity return will be selected to save the contents.in onActivityResult: 当图片选择活动返回时,将选择保存内容。在onActivityResult中:

          Bundle extras = data.getExtras();  
        if(extras != null ) {  
          Bitmap photo = extras.getParcelable("data");  
           ByteArrayOutputStream stream = new ByteArrayOutputStream();  
            photo.compress(Bitmap.CompressFormat.JPEG, 75, stream);  
          / / The stream to write to a file or directly using the
             }

It might work , but this is not a good practice to use com.android.camera.action.CROP as android doesn't have a Crop intent. 它可能会起作用,但这不是使用com.android.camera.action.CROP的好习惯,因为android没有Crop Intent。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM