上传头像

来源:互联网 发布:数据分析算法 知乎 编辑:程序博客网 时间:2024/06/09 04:46
 /**     * 上传头像     */    private void uploadHeadImage() {        View view = LayoutInflater.from(getActivity()).inflate(R.layout.shangchuan, null);        TextView btnCarema = (TextView) view.findViewById(R.id.btn_camera);        TextView btnPhoto = (TextView) view.findViewById(R.id.btn_photo);        TextView btnCancel = (TextView) view.findViewById(R.id.btn_cancel);        final PopupWindow popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);        popupWindow.setBackgroundDrawable(getResources().getDrawable(android.R.color.transparent));        popupWindow.setOutsideTouchable(true);        View parent = LayoutInflater.from(getActivity()).inflate(R.layout.activity_main, null);        popupWindow.showAtLocation(parent, Gravity.BOTTOM, 0, 0);        //popupWindow在弹窗的时候背景半透明        final WindowManager.LayoutParams params =getActivity(). getWindow().getAttributes();        params.alpha = 0.5f;        getActivity().getWindow().setAttributes(params);        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {            @Override            public void onDismiss() {                params.alpha = 1.0f;               getActivity(). getWindow().setAttributes(params);            }        });//按钮的点击事件        btnCarema.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                         takePicture();                popupWindow.dismiss();            }        });        btnPhoto.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                Intent openAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT);openAlbumIntent.setType("image/*");     startActivityForResult(openAlbumIntent, CHOOSE_PICTURE);                popupWindow.dismiss();            }        });        btnCancel.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                popupWindow.dismiss();        }        });    }
//调用相机
private void takePicture() {    String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};    if (Build.VERSION.SDK_INT >= 23) {        // 需要申请动态权限        int check = ContextCompat.checkSelfPermission(getActivity(), permissions[0]);        // 权限是否已经 授权 GRANTED---授权 DINIED---拒绝        if (check != PackageManager.PERMISSION_GRANTED) {            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);        }    }    Intent openCameraIntent = new Intent(            MediaStore.ACTION_IMAGE_CAPTURE);    File file = new File(Environment            .getExternalStorageDirectory(), "image.jpg");    //判断是否是AndroidN以及更高的版本    if (Build.VERSION.SDK_INT >= 24) {        openCameraIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);        tempUri = FileProvider.getUriForFile(getActivity(), "com.lt.uploadpicdemo.fileProvider", file);    } else {        tempUri = Uri.fromFile(new File(Environment                .getExternalStorageDirectory(), "image.jpg"));    }    // 指定照片保存路径(SD卡),image.jpg为一个临时文件,每次拍照后这个图片都会被替换    openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);    startActivityForResult(openCameraIntent, TAKE_PICTURE);}
/** * 裁剪图片方法实现 * * @param uri */protected void startPhotoZoom(Uri uri) {    if (uri == null) {        Log.i("tag", "The uri is not exist.");    }    tempUri = 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, CROP_SMALL_PICTURE);}/** * 保存裁剪之后的图片数据 * * @param */protected void setImageToView(Intent data) {    Bundle extras = data.getExtras();    if (extras != null) {        Bitmap photo = extras.getParcelable("data");        Log.d(TAG,"setImageToView:"+photo);        photo = ImageUtils.toRoundBitmap(photo);        // 这个时候的图片已经被处理成圆形的了        Log.d("lllll",photo.toString());                touxiang.setImageBitmap(photo);        uploadPic(photo);    }}
private void uploadPic(Bitmap bitmap) {    // 上传至服务器    // ... 可以在这里把Bitmap转换成file,然后得到fileurl,做文件上传操作    // 注意这里得到的图片已经是圆形图片了    // bitmap是没有做个圆形处理的,但已经被裁剪了    String imagePath = ImageUtils.savePhoto(bitmap, Environment            .getExternalStorageDirectory().getAbsolutePath(), String            .valueOf(System.currentTimeMillis()));    Log.e("imagePath", imagePath+"");    if(imagePath != null){        // 拿着imagePath上传了        // ...        //url 上传的服务器路径..file上传的文件,文件就是File类型的        //fileName文件名...例如aaa.jpg        //map<> params 除了文件之后,其他参数放到map集合中,例如uid,token,,如果没有其他参数传null        String[] split = imagePath.split("\\/");        String s = split[4];        Log.d("ffff",s);        File f2 = new File(Environment.getExternalStorageDirectory(),s);//上传的是SD卡中根目录下abc.jpg        Map<String, String> params = new HashMap<>();        params.put("uid","2766");       params.put("token","45B0E7B42F127F4991086773D396D525");        Log.d("rrrr",f2.toString());        OkHttp3Util.uploadFile("https://www.zhaoapi.cn/file/upload",f2,"alkkk.jpg",params);    }}
@Overridepublic void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,                                       @NonNull int[] grantResults) {    super.onRequestPermissionsResult(requestCode, permissions, grantResults);    if (requestCode == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {    } else {        // 没有获取 到权限,从新请求,或者关闭app        Toast.makeText(getActivity(), "需要存储权限", Toast.LENGTH_SHORT).show();    }}
//回调方法
if (resultCode == RESULT_OK) {   switch (requestCode) {        case TAKE_PICTURE:            Log.d("jjjjj","进来了");            CommonUtils.runOnUIThread(new Runnable() {                @Override                public void run() {                    Bitmap bm = data.getParcelableExtra("data");                    // 把图像显示到img                    touxiang.setImageBitmap(bm);                    startPhotoZoom(tempUri);                }            });            break;        case CHOOSE_PICTURE:            Log.d("jjjjj","进来2");            startPhotoZoom(data.getData()); // 开始对图片进行裁剪处理            break;        case CROP_SMALL_PICTURE:            CommonUtils.runOnUIThread(new Runnable() {                @Override                public void run() {                    if (data != null) {             /*   Bitmap bm2 = data.getParcelableExtra("data");                Log.d("yyyy",bm2.toString());                // 把图像显示到img                touxiang.setImageBitmap(bm2);*/                        setImageToView(data); // 让刚才选择裁剪得到的图片显示在界面上                        Log.d("jjjjj","进来3");                    }                }            });            break;    }
}