Call android system camera combined with android-crop crop images

Replace the application in a user's head, taking pictures and generally have two ways to select a photo from the gallery, and now there are many online open source, but many are too complicated. The Android-crop this library is relatively small, the code is not complicated, more suitable, but it did not take pictures of this function, we need to integrate into their own.

Call system camera to take pictures

  1. Return thumbnails of pictures
 // 调用系统的拍照
    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    }

OnActivityResult rewrite method, the camera system will return thumbnails

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        Bundle extras = data.getExtras();
        Bitmap imageBitmap = (Bitmap) extras.get("data");
        mImageView.setImageBitmap(imageBitmap);
    }
}
  1. Return the whole picture
    . If the picture is full, there is usually an external memory of the phone, this time need to access external authority
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
                     android:maxSdkVersion="18"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Permission is not required WRTE_EXTERNAL_STORAGE 4.4 and above, so we add the android: maxSdkVersion = "18"

Because it is the whole picture, the picture will be a great general, we can not return all the data as above, otherwise it is easy to appear OOM, so when the camera is set to start a specific path to save the picture, the camera can be used directly after this success the path

// 图片路径
 private Uri mCurrentPhotoUri;

// 拍照
private void dispatchTakePictureIntent() {
   Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
   if (takePictureIntent.resolveActivity(mContext.getPackageManager()) != null) {
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (photoFile != null){
                Uri photoUri = FileProvider.getUriForFile(mContext, "com.yxhuang.fileprovider", photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);

                mCurrentPhotoUri = photoUri;

                startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
            }
        }
    }

 // 创建图片路径
 private File createImageFile() throws IOException {
   String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = mContext.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,      /* prefix */
                ".jpg",             /* suffix */
                storageDir          /* directory */
        );

        return image;
    }

Uri when creating pictures using the FileProvider, FileProvider just a subclass of ContentProvider. For easy sharing files.
FileProvider some configuration
in the node at Manifext.xml

<!--自定义URI 需要 provider -->
<provider
    android:name="android.support.v4.content.FileProvider"
            android:authorities="com.yxhuang.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths">
            </meta-data>
        </provider>

Wherein the content of the authorities to the same FileProvider.getUriForFile () method of the second parameter.

But also for android: resource configured
res / xml / file_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="image_file" 
            path="Android/data/com.yxhuang/files/Pictures"/>
</paths>

Use open source library android-crop crop images

Android-crop is a relatively simple image cropping library. Specific use GitHub to see the Demo. Here we combine photographs used together.
Above we are ready to take pictures, we need to be processed in onActivityForResult () method

 @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 拍照返回
        if (resultCode == RESULT_OK){
            if (requestCode == REQUEST_IMAGE_CAPTURE){
                beginCrop(mCurrentPhotoUri);
            } else if (requestCode == Crop.REQUEST_PICK){
                beginCrop(data.getData());
            }
        }

        // 裁剪
        if (requestCode == Crop.REQUEST_CROP){
            handleCrop(resultCode, data);
        }
    }

// 开始裁剪
private void beginCrop(Uri source){
     Uri destination = Uri.fromFile(new File(mContext.getCacheDir(), "cropped"));
         // start() 方法根据其的需求选择不同的重载方法
        Crop.of(source, destination).asSquare().start(getActivity(), MineFragment.this);
    }

// 将裁剪回来的数据进行处理
 private void handleCrop(int resultCode, Intent result){
        if (resultCode == RESULT_OK){
            mImageView.setImageURI(Crop.getOutput(result));
        } else if (resultCode == Crop.RESULT_ERROR){
            Toast.makeText(mContext, 
                    Crop.getError(result).getMessage(), 
                    Toast.LENGTH_SHORT).show();
        }
    }

Write pictures described here

Published 58 original articles · won praise 20 · views 90000 +

Guess you like

Origin blog.csdn.net/yxhuang2008/article/details/53929953