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; }