1.res下新建xml文件然后新建file_paths.xml文件
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<!--填写你要所要申请访问的目录地址,name最好是你的目录名,path是你要申请的目录-->
<external-path name="camera_photos" path="." />
<external-path name="cache" path="Android/data/com.wsw.myapplication/cache" />
<external-path name="images" path="Pictures/" />
<external-path name="dcim" path="DCIM/" />
</paths>
2.配置provider
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.wsw.myapplication.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"/>
</provider>
3.布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical">
<Button
android:id="@+id/take_photo"
android:layout_width="match_parent"
android:layout_height="45dp"
android:text="拍照"/>
<ImageView
android:id="@+id/iv_img"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@mipmap/ic_launcher"/>
</LinearLayout>
4.代码
public class MainActivity extends Activity implements View.OnClickListener {
/*上传图片*/
boolean p = false;
Button btn_photo, btn_camera, btn_cancel2,take_photo;
ImageView iv_img;
String uploadFile;
private Dialog dialog;
public final String USER_IMAGE_NAME = "image.png";
public final String USER_CROP_IMAGE_NAME = "temporary.png";
public Uri imageUriFromCamera;
public Uri cropImageUri;
public final int GET_IMAGE_BY_CAMERA_U = 5001;
public final int GET_IMAGE_BY_CAMERA_U1 = 5002;
public final int CROP_IMAGE_U = 5003;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
take_photo=findViewById(R.id.take_photo);
iv_img=findViewById(R.id.iv_img);
take_photo.setOnClickListener(this);
}
private void showDialog() {
View view = getLayoutInflater().inflate(R.layout.photo_choose_dialog,
null);
btn_photo = (Button) view.findViewById(R.id.btn_photo);
btn_camera = (Button) view.findViewById(R.id.btn_camera);
btn_cancel2 = (Button) view.findViewById(R.id.btn_cancel2);
btn_photo.setOnClickListener(this);
btn_camera.setOnClickListener(this);
btn_cancel2.setOnClickListener(this);
dialog = new Dialog(this);
dialog.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
Window window = dialog.getWindow();
// 设置显示动画
WindowManager.LayoutParams wl = window.getAttributes();
wl.x = 0;
wl.y = getWindowManager().getDefaultDisplay().getHeight();
// 以下这两句是为了保证按钮可以水平满屏
wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
// 设置显示位置
dialog.onWindowAttributesChanged(wl);
// 设置点击外围解散
dialog.setCanceledOnTouchOutside(true);
dialog.show();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.take_photo:
showDialog();
break;
case R.id.btn_photo:
dialog.dismiss();
Intent mGalleryIntent = new Intent();
mGalleryIntent.setType("image/*");
mGalleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(mGalleryIntent, GET_IMAGE_BY_CAMERA_U1);
break;
case R.id.btn_camera:
dialog.dismiss();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // 或者 android.os.Build.VERSION_CODES.KITKAT这个常量的值是19
Log.d("MainActivity", "进入权限");
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File photoFile = createImagePathFile(MainActivity.this);
intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
/*
* 这里就是高版本需要注意的,需用使用FileProvider来获取Uri,同时需要注意getUriForFile
* 方法第二个参数要与AndroidManifest.xml中provider的里面的属性authorities的值一致
* */
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
imageUriFromCamera = FileProvider.getUriForFile(MainActivity.this,
"com.wsw.myapplication.fileprovider", photoFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUriFromCamera);
startActivityForResult(intent, GET_IMAGE_BY_CAMERA_U);
} else {
imageUriFromCamera = createImagePathUri(MainActivity.this);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUriFromCamera);
startActivityForResult(intent, GET_IMAGE_BY_CAMERA_U);
}
break;
case R.id.btn_cancel2:
dialog.dismiss();
break;
}
}
protected boolean isHaveSdCard() {
boolean isHave = false;
String state = Environment.getExternalStorageState();
if (state != null && Environment.MEDIA_MOUNTED.equals(state)
&& !Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
isHave = true;
}
return isHave;
}
//获取图片
protected void getImageToView(String data) {
// Bundle mBundle = data.getExtras();
if (data != null) {
String root = "";
if (isHaveSdCard()) {
root = Environment.getExternalStorageDirectory() + "/";
}
Bitmap imageBitmap = GetBitmap(data, 320, 320);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.PNG, 70, baos);
iv_img.setImageBitmap(imageBitmap);
uploadFile = FileUtilcll.saveFile(this, "picName.jpg", imageBitmap);
}
}
public Uri createImagePathUri(Activity activity) {
//文件目录可以根据自己的需要自行定义
Uri imageFilePath;
File file = new File(activity.getExternalCacheDir(), USER_IMAGE_NAME);
imageFilePath = Uri.fromFile(file);
return imageFilePath;
}
public File createImagePathFile(Activity activity) {
//文件目录可以根据自己的需要自行定义
Uri imageFilePath;
File file = new File(activity.getExternalCacheDir(), USER_IMAGE_NAME);
imageFilePath = Uri.fromFile(file);
return file;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
System.out.println(requestCode);
System.out.println("数据" + resultCode + "" + this.RESULT_OK);
if (resultCode != this.RESULT_CANCELED) {
switch (requestCode) {
case GET_IMAGE_BY_CAMERA_U:
/*
* 这里我做了一下调用系统切图,高版本也有需要注意的地方
* */
if (imageUriFromCamera != null) {
cropImage(imageUriFromCamera, 1, 1, CROP_IMAGE_U);
break;
}
break;
case GET_IMAGE_BY_CAMERA_U1:
/*
* 这里我做了一下调用系统切图,高版本也有需要注意的地方
* */
if (data == null) {
return;
}
Uri mUri = data.getData();
cropImage(mUri, 1, 1, CROP_IMAGE_U);
break;
case CROP_IMAGE_U:
final String s = getExternalCacheDir() + "/" + USER_CROP_IMAGE_NAME;
getImageToView(s);
break;
default:
break;
}
}
}
//裁剪
public void cropImage(Uri imageUri, int aspectX, int aspectY,
int return_flag) {
File file = new File(this.getExternalCacheDir(), USER_CROP_IMAGE_NAME);
Intent intent = new Intent("com.android.camera.action.CROP");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//高版本一定要加上这两句话,做一下临时的Uri
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
FileProvider.getUriForFile(MainActivity.this, "com.guangshuai.myapplication.fileprovider", file);
}
cropImageUri = Uri.fromFile(file);
intent.setDataAndType(imageUri, "image/*");
intent.putExtra("crop", "true");
if (Build.MODEL.contains("HUAWEI")) {//华为特殊处理 不然会显示圆
intent.putExtra("aspectX", 0.1);
intent.putExtra("aspectY", 0.1);
} else {
intent.putExtra("aspectX", 0.1);
intent.putExtra("aspectY", 0.1);
}
intent.putExtra("outputX", 800);
intent.putExtra("outputY", 800);
/* intent.putExtra("return-data", true);
intent.putExtra("scale", true);*/
intent.putExtra(MediaStore.EXTRA_OUTPUT, cropImageUri);
startActivityForResult(intent, return_flag);
}
public Bitmap GetBitmap(String path, int w, int h) {
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
BitmapFactory.decodeFile(path, opts);
int width = opts.outWidth;
int height = opts.outHeight;
float scaleWidth = 0.f, scaleHeight = 0.f;
if (width > w || height > h) {
scaleWidth = ((float) width) / w;
scaleHeight = ((float) height) / h;
}
opts.inJustDecodeBounds = false;
float scale = Math.max(scaleWidth, scaleHeight);
opts.inSampleSize = (int) scale;
WeakReference<Bitmap> weak = new WeakReference<Bitmap>(
BitmapFactory.decodeFile(path, opts));
return Bitmap.createScaledBitmap(weak.get(), w, h, true);
}
}