调用系统相机和相册,并且裁剪成圆形图片(解决6.0,7.0,8.0版本问题)

之前写过一篇博客,那篇博客对7.0手机裁剪图片的问题没有进行解决,现在对之前的那篇博客进行补充,解决了Android6.0,7.0,8.0版本问题,不仅可以调用相册,相机,还可以将图片保存到本地,并且裁剪成圆形图片

必要的权限:

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

在res文件下建一个文件夹xml  xml文件夹下一个文件file_path

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">

    <external-path
        name="external_storage_root"
        path="." />
</paths>

AndroidManifest:

<application
       ...
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.example.jingqian.camera.fileprovider"
            android:grantUriPermissions="true"
            android:exported="false">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_path">
            </meta-data>
        </provider>
    </application>

MainActivity布局:

<ImageButton
        android:id="@+id/iv_head"
        android:layout_width="120dp"
        android:layout_height="120dp"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp"
        android:background="@null"
        android:scaleType="fitXY"
        android:src="@drawable/ic_launcher_background" />

PopupWindow布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#00000000"
    android:gravity="bottom"
    android:orientation="vertical"
    android:padding="5dip" >

    <Button
        android:id="@+id/btn_picture"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/photo_gallery_selector"
        android:paddingBottom="10dip"
        android:paddingTop="10dip"
        android:text="图库"
        android:textSize="16sp" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="0.5dip"
        android:background="#DAD9DB" />

    <Button
        android:id="@+id/btn_photo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/photo_camera_selector"
        android:paddingBottom="10dip"
        android:paddingTop="10dip"
        android:text="拍照"
        android:textSize="16sp" />

    <Button
        android:id="@+id/btn_cancle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dip"
        android:background="@drawable/photo_cancel_selector"
        android:paddingBottom="10dip"
        android:paddingTop="10dip"
        android:text="取消"
        android:textSize="16sp" />

</LinearLayout>

MainAtivity中代码:

   //这是popupWindow中的相册按钮,相机按钮,取消按钮
    private Button btn_picture, btn_photo, btn_cancle;
   //头像控件
    private ImageButton ivHead;

    private Bitmap head;// 头像Bitmap
    @SuppressLint("SdCardPath")
    private static String path = "/sdcard/myHead/";// sd路径
    private Uri imageUri;
    private Uri uri;

onCreate方法:

        DongTaiShare();
        ivHead = (ImageButton) findViewById(R.id.iv_head);
        ivHead.setOnClickListener(this);

       

头像的点击事件里:

        //得到PopupWindow的视图
        View view = getLayoutInflater().inflate(R.layout.photo_choose_dialog, null);
        //给弹框设置样式
        final Dialog dialog = new Dialog(this, R.style.transparentFrameWindowStyle);
        dialog.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        Window window = dialog.getWindow();
        // 设置显示动画
        window.setWindowAnimations(R.style.main_menu_animstyle);
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.y = getWindowManager().getDefaultDisplay().getHeight();
        // 以下这两句是为了保证按钮可以水平满屏
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;

        // 设置显示位置
        dialog.onWindowAttributesChanged(wl);
        // 设置点击外围解散
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();

        btn_picture = (Button) window.findViewById(R.id.btn_picture);
        btn_photo = (Button) window.findViewById(R.id.btn_photo);
        btn_cancle = (Button) window.findViewById(R.id.btn_cancle);
        btn_picture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //调用系统相册
                Intent intent1 = new Intent(Intent.ACTION_PICK, null);
                intent1.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent1, 1);
                dialog.dismiss();
            }
        });
        btn_photo.setOnClickListener(new View.OnClickListener() {


            @Override
            public void onClick(View v) {
                //调用系统相机
                Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                File file = new File(Environment.getExternalStorageDirectory(), "head.jpg");
//判断手机版本号,这里是7.0以上的
                if (Build.VERSION.SDK_INT >= 24) {
                    uri = FileProvider.getUriForFile(MainActivity.this, "com.example.jingqian.camera.fileprovider", file);

                } else {
                    uri = Uri.fromFile(file); //7.0以下
                }


                intent2.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                startActivityForResult(intent2, 5);
                dialog.dismiss();
            }
        });
        btn_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

动态权限

private void DongTaiShare() {
        if (Build.VERSION.SDK_INT >= 23) {
            String[] mPermissionList = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CALL_PHONE, Manifest.permission.READ_LOGS, Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.SET_DEBUG_APP, Manifest.permission.SYSTEM_ALERT_WINDOW, Manifest.permission.GET_ACCOUNTS, Manifest.permission.WRITE_APN_SETTINGS, Manifest.permission.CAMERA};
            ActivityCompat.requestPermissions(this, mPermissionList, 123);
        }

    }

在MainActivity中的一些方法

 private void startPhotoZoom(Uri uri) {
        File CropPhoto = new File(getExternalCacheDir(), "Crop.jpg");//这个是创建一个截取后的图片路径和名称。
        try {
            if (CropPhoto.exists()) {
                CropPhoto.delete();
            }
            CropPhoto.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        imageUri = Uri.fromFile(CropPhoto);
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
        }
        intent.putExtra("crop", "true");
        intent.putExtra("scale", true);

        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

        //输出的宽高

        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);

        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        startActivityForResult(intent, 6);//这里的RESULT_REQUEST_CODE是在startActivityForResult里使用的返回值。
    }






    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {
                    cropPhoto(data.getData());// 裁剪图片
                }

                break;
            case 2:
                if (resultCode == RESULT_OK) {
//                    File file = new File(Environment.getExternalStorageDirectory() + "/head.jpg");
//                    Uri uri = Uri.fromFile(file);
                    File file = new File(Environment.getExternalStorageDirectory(), "head.jpg");
                    Uri uri = FileProvider.getUriForFile(MainActivity.this, "com.example.jingqian.camera.fileprovider", file);
                    cropPhoto(uri);// 裁剪图片


//                    Bitmap bitmap= data.getParcelableExtra("data");
//                    ivHead.setImageBitmap(bitmap);
                }

                break;
            case 3:
                if (data != null) {
                    Bundle extras = data.getExtras();
                    head = extras.getParcelable("data");
                    if (head != null) {
                        /**
                         * 上传服务器代码
                         */
                        setPicToView(head);// 保存在SD卡中
                        ivHead.setImageBitmap(toRoundBitmap(head));// 用ImageView显示出来
                    }
                }
                break;
            case 5:
                startPhotoZoom(uri);
                break;
            case 6:
                if (resultCode == RESULT_OK) {
                    try {
                        Log.e("=====",imageUri.toString());

                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                        ivHead.setImageBitmap(toRoundBitmap(bitmap));
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                break;
            default:
                break;

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    ;

    /**
     * 调用系统的裁剪
     *
     * @param uri
     */
    public void cropPhoto(Uri uri) {

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 3);
    }

    private void setPicToView(Bitmap mBitmap) {
        String sdStatus = Environment.getExternalStorageState();
        if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
            return;
        }
        FileOutputStream b = null;
        File file = new File(path);
        file.mkdirs();// 创建文件夹
        String fileName = path + "head.jpg";// 图片名字
        try {
            b = new FileOutputStream(fileName);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭流
                b.flush();
                b.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * 把bitmap转成圆形
     */
    public Bitmap toRoundBitmap(Bitmap bitmap) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        int r = 0;
        // 取最短边做边长
        if (width < height) {
            r = width;
        } else {
            r = height;
        }
        // 构建一个bitmap
        Bitmap backgroundBm = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        // new一个Canvas,在backgroundBmp上画图
        Canvas canvas = new Canvas(backgroundBm);
        Paint p = new Paint();
        // 设置边缘光滑,去掉锯齿
        p.setAntiAlias(true);
        RectF rect = new RectF(0, 0, r, r);
        // 通过制定的rect画一个圆角矩形,当圆角X轴方向的半径等于Y轴方向的半径时,
        // 且都等于r/2时,画出来的圆角矩形就是圆形
        canvas.drawRoundRect(rect, r / 2, r / 2, p);
        // 设置当两个图形相交时的模式,SRC_IN为取SRC图形相交的部分,多余的将被去掉
        p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        // canvas将bitmap画在backgroundBmp上
        canvas.drawBitmap(bitmap, null, rect, p);
        return backgroundBm;
    }

还有点击头像时popupWindow时从下往上滑出的,所以还要添加一些动画,

在res文件下建anim文件夹   文件夹下两个文件photo_dialog_in_anim.xml   和   photo_dialog_out_anim.xml

photo_dialog_in_anim.xml :

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >

    <translate
        android:duration="500"
        android:fromXDelta="0"
        android:fromYDelta="1000"
        android:toXDelta="0"
        android:toYDelta="0" />

</set>

photo_dialog_out_anim.xml:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >

    <translate
        android:duration="500"
        android:fromXDelta="0"
        android:fromYDelta="0"
        android:toXDelta="0"
        android:toYDelta="1000" />

</set>

在style下设置:

<style name="main_menu_animstyle">
        <item name="android:windowEnterAnimation">@anim/photo_dialog_in_anim</item>
        <item name="android:windowExitAnimation">@anim/photo_dialog_out_anim</item>
    </style>

这样就可以完美实现调用相册和相机并且裁剪图片了

May everyone be happy every day and everything go well!

猜你喜欢

转载自blog.csdn.net/jing_80/article/details/81127845