Android------简单实现换头像无头像上传

1.首先头像上传分为相机更换和相册更换,其次就是裁剪图片

public class MainActivity extends AppCompatActivity {

        @BindView(R.id.title)
        TextView title;
        @BindView(R.id.img)
        ImageView img;
        private PopupWindow popupWindow;
        private Unbinder bind;

        private File tempFile;
        //静态常量
        private static final int CAMEAR_REQUEST_CODE = 1;//回调到相机
        private static final int ALBUM_REQUEST_CODE = 2;//回调到相册
        private static final int CROP_REQUEST_CODE = 3;//回调剪切

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            bind = ButterKnife.bind(this);//butterknife实现找寻控件
            initView();
        }
        //底部弹窗
        public void showPopupWindow() {
            //显示设置的pop布局
            View inflate = LayoutInflater.from(this).inflate(R.layout.pop_item, null);//布局自定义,,,,也可以使用自定义的popupwindow
            TextView cream = inflate.findViewById(R.id.cream);//相机
            TextView ablum = inflate.findViewById(R.id.ablum);//相册
            TextView hide = inflate.findViewById(R.id.hide);//取消弹框
            popupWindow = new PopupWindow(inflate, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
            popupWindow.showAtLocation(inflate, Gravity.BOTTOM, 0, 0);
            cream.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //进入到相机调用
                    getPicFromCreame();
                }
            });
            ablum.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //进入到相册调用
                    getPicFromAblum();
                }
            });
            hide.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popupWindow.dismiss();
                }
            });
        }

        @OnClick(R.id.img)
        public void onViewClicked() {
            showPopupWindow();
        }

        /**
         * 从相机中取出图片
         */
        private void getPicFromCreame() {
            //用于保存调用相机拍照后所生成的文件
            //跳转到调用系统相机
            //判断版本
            // 如果在Android7.0以上,使用FileProvider获取Uri

            //先初始化出相机拍完照片后的存放路径
            tempFile = new File(Environment.getExternalStorageDirectory().getPath(), System.currentTimeMillis() + ".jpg");
            //跳转到调用系统相机(跳转系统相机用到的是intent隐式意图来进行跳转)
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            //跳转前需要对当前的Android版本进行判断,因为Android6.0以上的版本需要权限
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // 如果在Android7.0以上,使用FileProvider获取Uri
                intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);//此操作是app之间数据传递所以这个是ContentProvider临时权限来访问
                Uri contentUri = FileProvider.getUriForFile(MainActivity.this, "com.example.jiangkerun.touxiangdemo", tempFile);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);//传递路径
            } else { //否则使用Uri.fromFile(file)方法获取Uri
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
            }
            //由于需要回调
            startActivityForResult(intent, CAMEAR_REQUEST_CODE);
        }

        /**
         * 从相册中取到图片
         */
        public void getPicFromAblum() {
            Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
            photoPickerIntent.setType("image/*");
            startActivityForResult(photoPickerIntent, ALBUM_REQUEST_CODE);
        }

        /**
         * 图片裁剪
         */
        private void cropPhoto(Uri uri) {
            //隐式跳转到裁剪功能
            Intent intent = new Intent("com.android.camera.action.CROP");
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.setDataAndType(uri, "image/*");
            intent.putExtra("crop", "true");
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);

            intent.putExtra("outputX", 300);
            intent.putExtra("outputY", 300);
            intent.putExtra("return-data", true);

            startActivityForResult(intent, CROP_REQUEST_CODE);
        }

        @Override
        protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent intent) {
//        super.onActivityResult(requestCode, resultCode, data);
            switch (requestCode) {
                case CAMEAR_REQUEST_CODE:
                    //调用系统相机后返回
                    if (resultCode == RESULT_OK) {
                        //用相机返回的照片去调用剪裁也需要对Uri进行处理
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            Uri contentUri = FileProvider.getUriForFile(MainActivity.this, "com.hansion.chosehead", tempFile);
                            cropPhoto(contentUri);
                        } else {
                            cropPhoto(Uri.fromFile(tempFile));
                        }
                    }
                    break;
                case ALBUM_REQUEST_CODE:
                    //调用系统相册后返回
                    if (resultCode == RESULT_OK) {
                        Uri uri = intent.getData();
                        cropPhoto(uri);
                    }
                    break;
                case CROP_REQUEST_CODE:
                    Bundle bundle = intent.getExtras();
                    if (bundle != null) {
                        //在这里获得了剪裁后的Bitmap对象,可以用于上传
                        Bitmap image = bundle.getParcelable("data");
                        //设置到ImageView上
                        img.setImageBitmap(image);
                        //也可以进行一些保存、压缩等操作后上传
//                    String path = saveImage("crop", image);
                    }
                    break;
            }
        }
		//生成文件路径
        public String saveImage(String name, Bitmap bmp) {
            File appDir = new File(Environment.getExternalStorageDirectory().getPath());
            if (!appDir.exists()) {
                appDir.mkdir();
            }
            String fileName = name + ".jpg";
            File file = new File(appDir, fileName);
            try {
                FileOutputStream fos = new FileOutputStream(file);
                bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
                fos.flush();
                fos.close();
                return file.getAbsolutePath();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onDestroy() {
            super.onDestroy();
            bind.unbind();
        }
}

你可能感兴趣的:(android)