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

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

    

在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 完毕 接下来就是 回调了

@Overrideprotected 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转成filepublic 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;}

 

更多相关文章

  1. 使用安卓SerialManagerService
  2. Android(安卓)调用系统相机拍照并储存在本地
  3. Android(安卓)6.0 权限申请源码解析
  4. Android工具类ImgUtil选择相机和系统相册
  5. android studio 6.0以上动态申请权限的代码
  6. framework中自定义系统级权限
  7. Android(安卓)权限表
  8. Android创建快捷方式
  9. Android下的配置管理之道之gerrit权限管理

随机推荐

  1. Android Timer 实现方法
  2. android解压ZIP文件
  3. 获取Android各种系统信息
  4. 【实用工具】adb检测android设备
  5. Android Camera2 API 学习
  6. Android(安卓)最佳实践
  7. android 让 webView 中的超链接失效
  8. Android中MAC地址获取代码
  9. Android动态权限判断以及动态权限申请
  10. android工程引入第三方jar包,如果发现混淆