android 头像选择以及裁剪

纵饮孤独 提交于 2020-04-06 06:08:41

一、布局申明

<ImageView
                android:id="@+id/head_image"
                android:layout_width="80dp"
                android:layout_height="80dp"
                android:layout_centerHorizontal="true"
                android:background="@drawable/default_avatar" />

 

二、Activity中代码

private ImageView headImageView;
    
private BitmapUtil bitmapUtil = new BitmapUtil(this);private File headFile;


headImageView = (ImageView) findViewById(R.id.head_image);
        
        headImageView.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View v) {
                
                new android.app.AlertDialog.Builder(RegisterActivity.this)
                    .setTitle("头像选择")
                    .setNegativeButton("相册选取",
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                                bitmapUtil.doCropPhoto(RegisterActivity.this);
                            }
                        })
                    .setPositiveButton("相机拍照",
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                                String status = Environment.getExternalStorageState();
                                if (status.equals(Environment.MEDIA_MOUNTED)) {// 判断是否有SD卡
                                    bitmapUtil.doTakePhoto(RegisterActivity.this);// 用户点击了从照相机获取
                                }
                            }
                        }).show();
            }
        });

 

三、Activity回调方法

/**
     * 头像选择回调
     * resultCode:  正常返回-1   用户后退返回0
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.i("TAG", requestCode + " : " + resultCode);
        if(resultCode == RESULT_OK) {
            switch (requestCode) {
            
            case BitmapUtil.activity_result_camara_with_data: // 拍照
                try {
                    if (bitmapUtil.tempFile != null) {
                        bitmapUtil.cropImageByCamera();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case BitmapUtil.activity_result_cropimage_with_data:
                try {
                    if (bitmapUtil.tempFile != null) {
                        headFile = bitmapUtil.tempFile;
                        
                        Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(headFile));
                        headImageView.setImageBitmap(bitmap);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            }
        }
    }

 

四、工具类

public class BitmapUtil {

    public final static int activity_result_camara_with_data = 1006;
    public final static int activity_result_cropimage_with_data = 1007;

    public File tempFile;

    private Activity activity;

    public BitmapUtil(Activity activity) {
        super();
        this.activity = activity;
    }

    /**
     * 照相获取图片
     */
    public void selectPicFromCamera() {
//        if (!CommonUtils.isExitsSdcard()) {
//            Toast.makeText(activity, "SD卡不存在,不能拍照", Toast.LENGTH_SHORT).show();
//            return;
//        }

        if(createNewFile()) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));

            activity.startActivityForResult(intent, activity_result_camara_with_data);
        }
        
    }
    
    
    /**
     * 照相获取完成图片时候裁剪图片
     */
    public void cropImageByCamera() {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(Uri.fromFile(tempFile), "image/*");
        buildCropIntent(intent);
        
        activity.startActivityForResult(intent, activity_result_cropimage_with_data);
    }
    

    /**
     * 从图库获取图片
     */
    public void selectPicFromLocal() {
        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
        } else {
            intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        
        if(createNewFile()) {
            buildCropIntent(intent);
            
            activity.startActivityForResult(intent, activity_result_cropimage_with_data);
        }
    }
    
    /**
     * 构建截图的intent
     * @param intent
     */
    private void buildCropIntent(Intent intent) {
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 100);
        intent.putExtra("outputY", 100);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", true);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", false); // no face detection
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
    }
    
    /**
     * 创建新文件
     * @return
     */
    private boolean createNewFile() {
        if (!CommonUtils.isExitsSdcard()) {
            Toast.makeText(activity, "SD卡不存在", Toast.LENGTH_SHORT).show();
            return false;
        }
        tempFile = new File(Environment.getExternalStorageDirectory().getPath() + "/stchat" + "/images/" + System.currentTimeMillis() + ".jpg");
        if(!tempFile.getParentFile().exists()) {
            tempFile.getParentFile().mkdirs();
        }
        
        if(!tempFile.exists()) {
            try {
                tempFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }
    
    public static void setBitmap(ImageView view, String head_portrait) {
        // 设置用户头像
        Bitmap bitmap = BitmapFactory.decodeFile(head_portrait);
        if(bitmap != null) {
            view.setImageBitmap(bitmap);
        }
    }
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!