安卓上传头像(拍照,相册)

 首先要开启权限

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

布局文件

<?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:orientation="vertical" >

    <Button
        android:id="@+id/camera"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="相机" />

    <Button
        android:id="@+id/pick"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="相册" />

    <Button
        android:id="@+id/quxiao"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="取消" />

</LinearLayout>

代码块

在点击事件中设置弹框

myTouxiang.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                View view = View.inflate(getActivity(), R.layout.my_popwindow, null);
                popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                popupWindow.setBackgroundDrawable(new ColorDrawable(Color.BLUE));
                popupWindow.setOutsideTouchable(true);
                popupWindow.showAsDropDown(v);
                camera =  view.findViewById(R.id.camera);
                pick = view.findViewById(R.id.pick);
                quxiao = view.findViewById(R.id.quxiao);
                //打开相机
                camera.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        if (hasSdcard()) {
                            // 存到sdcard中
                            intent.putExtra(MediaStore.EXTRA_OUTPUT,
                                    Uri.fromFile(new File(path)));
                            //执行
                            startActivityForResult(intent, REQUEST_CAMEAR);
                            popupWindow.dismiss();
                        }
                    }
                });

                //打开相册
                pick.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //加载相册
                        Intent intent = new Intent(Intent.ACTION_PICK);
                        if (hasSdcard()) {
                            //设置图片格式
                            intent.setType("image/*");
                            //执行
                            startActivityForResult(intent, REQUEST_PICK);
                            popupWindow.dismiss();
                        }
                    }
                });

                //取消
                quxiao.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popupWindow.dismiss();
                    }
                });

            }
        });

 相机相册裁剪上传

private boolean hasSdcard() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 上传头像
     */



    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CAMEAR && resultCode == RESULT_OK) {
            //调取裁剪功能
            Intent intent = new Intent("com.android.camera.action.CROP");
            //将图片设置给裁剪
            intent.setDataAndType(Uri.fromFile(new File(path)), "image/*");
            //设置是否支持裁剪
            intent.putExtra("CROP", true);
            //设置宽高比
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            //设置显示大小
            intent.putExtra("outputX", 50);
            intent.putExtra("outputY", 50);
            //将图片返回给data
            intent.putExtra("return-data", true);
            startActivityForResult(intent, REQUEST_PICTRUE);
        }
        if (requestCode == REQUEST_PICK && resultCode == RESULT_OK) {
            //打开裁剪
            Intent intent = new Intent("com.android.camera.action.CROP");
            Uri uri = data.getData();
            //将图片设置给裁剪
            intent.setDataAndType(uri, "image/*");
            //设置是否可裁剪
            intent.putExtra("CROP", true);
            //设置宽高比
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            //设置输出
            intent.putExtra("outputX", 100);
            intent.putExtra("outputY", 100);
            //返回data
            intent.putExtra("return-data", true);
            startActivityForResult(intent, REQUEST_PICTRUE);
        }
        if (requestCode == REQUEST_PICTRUE && resultCode == RESULT_OK) {
            Bitmap bitmap = data.getParcelableExtra("data");
            myTouxiang.setImageBitmap(bitmap);
            try {
                file = saveFile(bitmap, "/image.png");
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
            }
            onFail(file);
        }
    }
    public void onFail(File file) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {//挂载状态
            if (file != null && file.exists()) {
                //图片请求体
                RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
                //对图片请求体对象,封装成multipart对象,文件表单对象
                MultipartBody.Part filePart = MultipartBody.Part.createFormData("image", file.getName(), requestBody);
                //P层进行网络请求

                MyHeadPresenter myHeadPresenter = new MyHeadPresenter();
                myHeadPresenter.setView(fragment_my);
                myHeadPresenter.loadData(userId,sessionId,filePart);
            } else {
                Toast.makeText(getActivity(), "请选择文件", Toast.LENGTH_LONG).show();
            }
        }
    }

    public File saveFile(Bitmap bm, String fileName) throws IOException {//将Bitmap类型的图片转化成file类型,便于上传到服务器
        String path = Environment.getExternalStorageDirectory() + "/Ask";
        File dirFile = new File(path);
        if(!dirFile.exists()){
            dirFile.mkdir();
        }
        File myCaptureFile = new File(path + fileName);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();
        return myCaptureFile;
    }

猜你喜欢

转载自blog.csdn.net/weixin_43731179/article/details/89488308