//android调用系统相机和相册进行拍照裁剪处理,解决不同安卓版本存在无法加载相册的问题,处理了是否有sd卡的存在的情况
private static final int IMAGE_REQUEST_CODE = 0;
private static final int SELECT_PIC_KITKAT = 3;
private static final int CAMERA_REQUEST_CODE = 1;
private static final int RESULT_REQUEST_CODE = 2;
private static final String IMAGE_FILE_NAME_01 = “face.jpg”;
private Uri personPath = null;
private Uri companyPath = null;
private static final String IMAGE_FILE_NAME_02= “logo.jpg”;
private Dialog mydialog;
private boolean isPic ;
private boolean isOpen =false;
private boolean sdCardExist;
//先创建路径
private void makeDir() {
//检查手机上是否有外部存储卡
sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
if(!sdCardExist)
{
}else{//如果存在SD卡,判断文件夹目录是否存在
//一级目录和二级目录必须分开创建
File dirFirstFile=new File(Environment
.getExternalStorageDirectory()+”/ttx”);//新建一级主目录
if(!dirFirstFile.exists()){//判断文件夹目录是否存在
dirFirstFile.mkdir();//如果不存在则创建
}
}
//执行完上述方法之后,如果手机sd才能用,则在sd卡上创建一个文件夹,如果sd卡不能用,则在默认系统根目录处创建一个文件夹
接下来新建一个自定义dialog来实现调取的功能
class Mydialog extends Dialog {
Context context;
RadioButton rbcamera, rbpic;
RadioGroup rgheaderchange;
public Mydialog(Context context) {
super(context);
this.context = context;
}
public Mydialog(Context context, int theme) {
super(context, theme);
this.context = context;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.dia_headerchange);
rbcamera = (RadioButton) findViewById(R.id.rb_camera);
rbpic = (RadioButton) findViewById(R.id.rb_pic);
rgheaderchange = (RadioGroup) findViewById(R.id.rg_headerchange);
rgheaderchange
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group,
int checkedId) {
if (rbcamera.getId() == checkedId) {
Intent intentFromCapture = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
// 判断存储卡是否可以用,可用进行存储
if (isPic) {
intentFromCapture.putExtra(
MediaStore.EXTRA_OUTPUT,
Uri.fromFile(new File(Environment
.getExternalStorageDirectory()+"/ttx",
IMAGE_FILE_NAME_01)));
}else{
intentFromCapture.putExtra(
MediaStore.EXTRA_OUTPUT,
Uri.fromFile(new File(Environment
.getExternalStorageDirectory()+"/ttx",
IMAGE_FILE_NAME_02)));
}
startActivityForResult(intentFromCapture,
CAMERA_REQUEST_CODE);
mydialog.dismiss();
} else {
// pickPhotoFromGallery();// 从相册中去获取
Intent intent=new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
startActivityForResult(intent,SELECT_PIC_KITKAT);
} else {
startActivityForResult(intent,IMAGE_REQUEST_CODE);
}
mydialog.cancel();
}
}
});
}
}
//实现返回方法进行处理
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// 结果码不等于取消时候
if (resultCode != Activity.RESULT_CANCELED) {
switch (requestCode) {
case IMAGE_REQUEST_CODE:
startPhotoZoom(data.getData());
break;
case SELECT_PIC_KITKAT:
startPhotoZoom(data.getData());
break;
case CAMERA_REQUEST_CODE:
if (!sdCardExist) {
//如果不存在SD卡,进行提示
Toast.makeText(getActivity(), "没有内存卡,无法拍照", Toast.LENGTH_SHORT).show();
getActivity().finish();
}else{
File tempFile =null;
if (isPic) {
tempFile = new File(Environment.getExternalStorageDirectory()+ "/ttx/",IMAGE_FILE_NAME_01);
}else{
tempFile = new File(Environment.getExternalStorageDirectory()+ "/ttx/",IMAGE_FILE_NAME_02);
}
startPhotoZoom(Uri.fromFile(tempFile));
}
break;
case RESULT_REQUEST_CODE:
Bundle bundle = data.getExtras();
Bitmap photo = bundle.getParcelable("data");
photo = ThumbnailUtils.extractThumbnail(photo, 50, 50);
if (isPic) {
mimg_card_add_pic.setImageBitmap(photo);
}else{
mimg_card_add_logo.setImageBitmap(photo);
}
saveBitmap(photo);
break;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
//实现裁剪方法
public void startPhotoZoom(Uri uri) {
if (uri == null) {
Log.i("tag", "The uri is not exist.");
return;
}
Intent intent = new Intent("com.android.camera.action.CROP");
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
String url=getPath(getActivity(),uri);
intent.setDataAndType(Uri.fromFile(new File(url)), "image/*");
}else{
intent.setDataAndType(uri, "image/*");
}
// 设置裁剪
intent.putExtra("crop", "true");
// aspectX aspectY 是宽高的比例
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
// outputX outputY 是裁剪图片宽高
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 200);
intent.putExtra("return-data", true);
startActivityForResult(intent, RESULT_REQUEST_CODE);
}
//保存的方法
public void saveBitmap(Bitmap mBitmap) {
File f=null;
if (isPic) {
f = new File(Environment.getExternalStorageDirectory(),IMAGE_FILE_NAME_01);
personPath = Uri.fromFile(f);
}else{
f = new File(Environment.getExternalStorageDirectory(),IMAGE_FILE_NAME_02);
companyPath = Uri.fromFile(f);
}
try {
f.createNewFile();
FileOutputStream fOut = null;
fOut = new FileOutputStream(f);
mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.flush();
fOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//以下是关键,原本uri返回的是file:///...来着的,android4.4返回的是content:///...
@SuppressLint("NewApi")
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] {
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is Google Photos.
*/
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
//至此,所有的方法都实现可以完美的通过运行,如果有不明白的可以给我留言。