android 9.0 拍照 相册选择 图片 裁切后进行 上传到服务器(亲测可用)

implementation 'com.github.bumptech.glide:glide:3.7.0'  //用来加载图片
implementation 'pub.devrel:easypermissions:1.3.0'

还要记得在清单文件中加入 以下代码

<provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="me.xifengwanzhao.provider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>

在activity 的oncreate 中加入

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
    StrictMode.setVmPolicy(builder.build());
}

 

主要代码 layout 就是一个触发事件的 Onclick

private String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
getPermission();//获取权限
getCameraDialog();//相机和相册
    //---------------------------
//获取权限
    private void getPermission() {
        if (EasyPermissions.hasPermissions(this, permissions)) {
            //已经打开权限
//            Toast.makeText(this, "已经申请相关权限", Toast.LENGTH_SHORT).show();
        } else {
            //没有打开相关权限、申请权限
            EasyPermissions.requestPermissions(this, "需要获取您的相册、照相使用权限", 1, permissions);
        }

    }

 

/**
 * 调取用户选择 相册 相机的弹窗
 */
private void getCameraDialog() {
    AlertDialog builder = new AlertDialog.Builder(SalesAdvanceOrderActivity.this)
            .setTitle("选择头像")
            .setPositiveButton("相机", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    selectCamera();
                }
            })
            .setNegativeButton("相册", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    selectPhoto();
                }
            })
            .show();
}

 

private static final int GET_BACKGROUND_FROM_CAPTURE_RESOULT = 1;
private static final int RESULT_REQUEST_CODE = 2;
private static final int TAKE_PHOTO = 3;
private Uri photoUri;   //相机拍照返回图片路径
private File outputImage;


//选择相机
private void selectCamera() {

    //创建file对象,用于存储拍照后的图片,这也是拍照成功后的照片路径
    outputImage = new File(this.getExternalCacheDir(), "camera_photos.jpg");
    try {
        //判断文件是否存在,存在删除,不存在创建
        if (outputImage.exists()) {
            outputImage.delete();
        }
        outputImage.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
    }
    photoUri = Uri.fromFile(outputImage);

    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
    startActivityForResult(intent, TAKE_PHOTO);

}

 

public static final String STR_IMAGE = "image/*";
//选择相册
private void selectPhoto(){
    Intent intent = new Intent(Intent.ACTION_PICK, null);
    intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, STR_IMAGE);
    startActivityForResult(intent, GET_BACKGROUND_FROM_CAPTURE_RESOULT);

}

相册和 拍照都已经vc 完毕 接下来就是 回调了

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    if (resultCode != RESULT_OK) return;

    switch (requestCode) {

        case GET_BACKGROUND_FROM_CAPTURE_RESOULT:   //相册返回
            photoUri = data.getData();
            cropRawPhoto(photoUri);
            break;


        case TAKE_PHOTO://   拍照返回
            cropRawPhoto(photoUri);

            break;

        case RESULT_REQUEST_CODE:   //裁剪完照片
            if (cropImgUri != null) {
                try {
                    Bitmap headImage = BitmapFactory.decodeStream(this.getContentResolver().openInputStream(cropImgUri));
                    mSalesAddImg.setImageBitmap(headImage);

                      File file = getFile(headImage);//把Bitmap转成File

                    //上传图片
                    OkHttpClient httpClient = new OkHttpClient();
                    MediaType mediaType = MediaType.parse("application/octet-stream");//设置类型,类型为八位字节流
                    RequestBody requestBody = RequestBody.create(mediaType, file);//把文件与类型放入请求体

                    MultipartBody multipartBody = new MultipartBody.Builder()
                            .setType(MultipartBody.FORM)
                            .addFormDataPart("image", file.getName(), requestBody)//文件名,请求体里的文件
                            .build();
                    Request request = new Request.Builder()
                            .url(UpUser_Img)
                            .post(multipartBody)
                            .build();
                    Call call = httpClient.newCall(request);
                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {

                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String string = response.body().string();
                            ImgBean imgBean = new Gson().fromJson(string, ImgBean.class);
                            if(imgBean.getStatus()==1){
                                    ImageUrl=imgBean.getThumb();
                            }
                        }
                    });



                } catch (Exception e) {
                    e.printStackTrace();
                }

            } else {
                Toast.makeText(this, "cropImgUri为空!", Toast.LENGTH_SHORT).show();
            }
            break;

    }


    super.onActivityResult(requestCode, resultCode, data);


}

 还有裁切的 方法

 private Uri cropImgUri;

    //裁剪图片
    public void cropRawPhoto(Uri uri) {
        //创建file文件,用于存储剪裁后的照片
          cropImage = new File(Environment.getExternalStorageDirectory(), "crop_image.jpg");
        String path = cropImage.getAbsolutePath();
        try {
            if (cropImage.exists()) {
                cropImage.delete();
            }
            cropImage.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        cropImgUri = Uri.fromFile(cropImage);
        Intent intent = new Intent("com.android.camera.action.CROP");
//设置源地址uri
        intent.setDataAndType(photoUri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 200);
        intent.putExtra("outputY", 200);
        intent.putExtra("scale", true);
//设置目的地址uri
        intent.putExtra(MediaStore.EXTRA_OUTPUT, cropImgUri);
//设置图片格式
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("return-data", false);
        intent.putExtra("noFaceDetection", true); // no face detection
        startActivityForResult(intent, RESULT_REQUEST_CODE);
    }

 

 

//把bitmap转成file
public File getFile(Bitmap bitmap) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos);
    File file = new File(Environment.getExternalStorageDirectory() + "/temp.jpg");
    try {
        file.createNewFile();
        FileOutputStream fos = new FileOutputStream(file);
        InputStream is = new ByteArrayInputStream(baos.toByteArray());
        int x = 0;
        byte[] b = new byte[1024 * 100];
        while ((x = is.read(b)) != -1) {
            fos.write(b, 0, x);
        }
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return file;
}

 


版权声明:本文为Jonly_W原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。