寫一個選擇圖片的utilsandroid
//選擇是否剪切圖片構造函數 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); }
圖片存儲app
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); }
相機方法ide
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); }
裁剪方法post
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卡Pathui
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(); }
設置裁剪是選擇框默認大小this
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; }
圖片filegoogle
private File getTempFile() { try { return new File(getSDCardPath() + "/temp_crop.jpg"); } catch (Exception e) { Log.d("harvic", e.getMessage()); } return null; }
計算圖片寬高設置壓縮比例spa
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; }
圖片路徑code
@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, "選擇圖片失敗"); } }
大功告成