写一个选择图片的utils
//选择是否剪切图片构造函数 public CropPhotoUtils(ResultPhoto rp, Context context, boolean crop) { mRp = rp; mContext = context; isCrop = crop; takeFile(); } public CropPhotoUtils(ResultPhoto rp, Context context) { this(rp, context, true); }
图片存储
public void takeFile() { String path = getSDCardPath(); File file = new File(path + "/temp.jpg"); mImageUri = Uri.fromFile(file); File cropFile = new File(getSDCardPath() + "/temp_crop.jpg"); mImageCropUri = Uri.fromFile(cropFile); }
相机方法
public void takeCamera() { Intent intent = null; intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//action is capture intent.putExtra("return-data", false); intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri); intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()); intent.putExtra("noFaceDetection", true); ((Activity) mContext).startActivityForResult(intent, RESULT_CAMERA_PATH); }
相册方法
public void takeAlbum() { Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null); intent.setType("image/*"); ((Activity) mContext).startActivityForResult(intent, RESULT_ALBUM_CROP_PATH); }
裁剪方法
public void cropImg(Uri uri, int width, final int tag) { Intent intent = new Intent("com.android.camera.action.CROP"); intent.setDataAndType(uri, "image/*"); intent.putExtra("crop", "true"); intent.putExtra("aspectX", 9998); intent.putExtra("aspectY", 9999); intent.putExtra("outputX", width); intent.putExtra("outputY", width); intent.putExtra("return-data", false); intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCropUri); intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()); intent.putExtra("noFaceDetection", true); ((Activity) mContext).startActivityForResult(intent, tag); }
取SD卡Path
public static String getSDCardPath() { String cmd = "cat /proc/mounts"; Runtime run = Runtime.getRuntime(); try { Process p = run.exec(cmd); BufferedInputStream in = new BufferedInputStream(p.getInputStream()); BufferedReader inBr = new BufferedReader(new InputStreamReader(in)); String lineStr; while ((lineStr = inBr.readLine()) != null) { if (lineStr.contains("sdcard") && lineStr.contains(".android_secure")) { String[] strArray = lineStr.split(" "); if (strArray != null && strArray.length >= 5) { String result = strArray[1].replace("/.android_secure", ""); return result; } } if (p.waitFor() != 0 && p.exitValue() == 1) { } } inBr.close(); in.close(); } catch (Exception e) { return Environment.getExternalStorageDirectory().getPath(); } return Environment.getExternalStorageDirectory().getPath(); }
设置裁剪是选择框默认大小
private Bitmap setScaleBitmap(Bitmap photo, int SCALE) { if (photo != null) { Bitmap smallBitmap = zoomBitmap(photo, photo.getWidth() / SCALE, photo.getHeight() / SCALE); photo.recycle(); return smallBitmap; } return null; }
图片file
private File getTempFile() { try { return new File(getSDCardPath() + "/temp_crop.jpg"); } catch (Exception e) { Log.d("harvic", e.getMessage()); } return null; }
计算图片宽高设置压缩比例
public Bitmap zoomBitmap(Bitmap bitmap, int width, int height) { int w = bitmap.getWidth(); int h = bitmap.getHeight(); Matrix matrix = new Matrix(); float scaleWidth = ((float) width / w); float scaleHeight = ((float) height / h); matrix.postScale(scaleWidth, scaleHeight); Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true); return newbmp; }
图片路径
@SuppressLint("NewApi") public static String parsePicturePath(Context context, Uri uri) { if (null == context || uri == null) return null; boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT; // DocumentUri if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) { // ExternalStorageDocumentsUri if (isExternalStorageDocumentsUri(uri)) { String docId = DocumentsContract.getDocumentId(uri); String[] splits = docId.split(":"); String type = splits[0]; if ("primary".equalsIgnoreCase(type)) { return Environment.getExternalStorageDirectory() + File.separator + splits[1]; } } // DownloadsDocumentsUri else if (isDownloadsDocumentsUri(uri)) { String docId = DocumentsContract.getDocumentId(uri); Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId)); return getDataColumn(context, contentUri, null, null); } // MediaDocumentsUri else if (isMediaDocumentsUri(uri)) { String docId = DocumentsContract.getDocumentId(uri); String[] split = docId.split(":"); 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; } String selection = "_id=?"; String[] selectionArgs = new String[]{split[1]}; return getDataColumn(context, contentUri, selection, selectionArgs); } } // MediaStore (general) else if ("content".equalsIgnoreCase(uri.getScheme())) { if (isGooglePhotosContentUri(uri)) return uri.getLastPathSegment(); return getDataColumn(context, uri, null, null); } // File else if ("file".equalsIgnoreCase(uri.getScheme())) { return uri.getPath(); } return null; }
private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) { Cursor cursor = null; String column = "_data"; String[] projection = {column}; try { cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null); if (cursor != null && cursor.moveToFirst()) { int index = cursor.getColumnIndexOrThrow(column); return cursor.getString(index); } } finally { try { if (cursor != null) cursor.close(); } catch (Exception e) { Log.e("harvic", e.getMessage()); } } return null; } private static boolean isExternalStorageDocumentsUri(Uri uri) { return "com.android.externalstorage.documents".equals(uri.getAuthority()); } private static boolean isDownloadsDocumentsUri(Uri uri) { return "com.android.providers.downloads.documents".equals(uri.getAuthority()); } private static boolean isMediaDocumentsUri(Uri uri) { return "com.android.providers.media.documents".equals(uri.getAuthority()); } private static boolean isGooglePhotosContentUri(Uri uri) { return "com.google.android.apps.photos.content".equals(uri.getAuthority()); }
保存图片
public void saveBitmap(Bitmap bm) { FileOutputStream out = null; if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) // 判断是否可以对SDcard进行操作 { // 获取SDCard指定目录下 String sdCardDir = Environment.getExternalStorageDirectory() + "/CoolImage/"; File dirFile = new File(sdCardDir); //目录转化成文件夹 if (!dirFile.exists()) { //如果不存在,那就建立这个文件夹 dirFile.mkdirs(); } //文件夹有啦,就可以保存图片啦 File file = new File(sdCardDir, System.currentTimeMillis() + ".jpg");// 在SDcard的目录下创建图片文,以当前时间为其命名 try { out = new FileOutputStream(file); bm.compress(Bitmap.CompressFormat.JPEG, 90, out); // Toast.makeText(mContext, "保存已经至" + Environment.getExternalStorageDirectory() + "/CoolImage/" + "目录文件夹下", Toast.LENGTH_SHORT).show(); } catch (FileNotFoundException e) { e.printStackTrace(); } try { out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } mRp.getBitmap(bm, file.getAbsolutePath()); } }
需要的接口
public interface ResultPhoto { int RESULT_CANCEL = 1; int RESULT_FAILED = 2; void getBitmap(Bitmap bitmap, String path); void cancel(int type); }
处理 onActivityResult
public void ActivityResult(int requestCode, int resultCode, Intent data, int width) { Log.i("RESULT", resultCode + ""); if (resultCode == Activity.RESULT_OK) { switch (requestCode) { case RESULT_CAMERA_PATH: if (isCrop) { cropImg(mImageUri, width, RESULT_CAMERA_CROP_PATH_RESULT); } else { Bitmap bitmap = null; try { bitmap = BitmapFactory.decodeStream(mContext.getContentResolver().openInputStream(mImageUri)); saveBitmap(bitmap); } catch (FileNotFoundException e) { e.printStackTrace(); } } break; case RESULT_CAMERA_CROP_PATH_RESULT: try { Bitmap bitmap = BitmapFactory.decodeStream(mContext.getContentResolver().openInputStream(mImageCropUri)); saveBitmap(bitmap); } catch (FileNotFoundException e) { e.printStackTrace(); } break; case RESULT_ALBUM_CROP_PATH: { String picPath = parsePicturePath(mContext, data.getData()); File file = new File(picPath); Uri uri = Uri.fromFile(file); if (isCrop) { cropImg(uri, width, RESULT_ALBUM_CROP_PATH_RESULT); } else { Bitmap bitmap = BitmapFactory.decodeFile(picPath, null); if (bitmap != null) { Bitmap smallBmp = setScaleBitmap(bitmap, 2); saveBitmap(smallBmp); } } } break; case RESULT_ALBUM_CROP_PATH_RESULT: { Bitmap bitmap = BitmapFactory.decodeFile(getTempFile().getAbsolutePath(), null); if (bitmap != null) { Bitmap smallBmp = setScaleBitmap(bitmap, 2); saveBitmap(smallBmp); } } break; } } else if (resultCode == Activity.RESULT_CANCELED) { mRp.cancel(ResultPhoto.RESULT_CANCEL); return; } else { mRp.cancel(ResultPhoto.RESULT_FAILED); return; } }
成员变量
public static final int RESULT_CAMERA_PATH = 100; public static final int RESULT_CAMERA_CROP_PATH_RESULT = 301; private static final int RESULT_ALBUM_CROP_PATH = 302; private static final int RESULT_ALBUM_CROP_PATH_RESULT = 401; private Uri mImageUri; private Uri mImageCropUri; private ResultPhoto mRp; private Context mContext; private boolean isCrop;
Activity中onActivityResult()
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); mCpu.ActivityResult(requestCode, resultCode, data, mWidth); }
触发事件
@Override public void onClick(View view) { mCpu = new CropPhotoUtils(this, CameraCropActivity.this); switch (view.getId()) { case R.id.btn_camera_only: mCpu.takeCamera(); break; case R.id.btn_album: mCpu.takeAlbum(); break; default: break; } }
实现接口
@Override public void getBitmap(Bitmap bitmap, String path) { mImage.setImageBitmap(bitmap); } @Override public void cancel(int type) { if (type == 1) { ToastUtils.show(CameraCropActivity.this, "已取消选择图片"); } else { ToastUtils.show(CameraCropActivity.this, "选择图片失败"); } }
大功告成