Android-->相册,摄像头获取图片,图片路径,以及剪裁图片

本文介绍如何从相册,摄像头中获取图片Bitmap和图片的路径Path.
并且实现可以剪裁图片,和压缩图片.

1:打开图片选择器(系统默认就提供了)

static final int REQUEST_CODE_PHOTO = 100;
public void getPhotoFromPhotos() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "选择图片"), REQUEST_CODE_PHOTO);
}

2:打开相机拍照图片

static final int REQUEST_CODE_CAMERA = 101;
public void getPhotoFromCamera() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
    imageUri = Uri.fromFile(new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
            UUID.randomUUID() + ".jpg"));//需要提供图片的保存路径
    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); // set the image file name
    startActivityForResult(intent, REQUEST_CODE_CAMERA);
}

3:通过图片路径剪裁图片

/**
 * 用给定的uri,调用 裁剪程序
 */
private void cropImageByUri(Uri uri, int outputX, int outputY, int requestCode) {
    Intent intent = new Intent("com.android.camera.action.CROP");
    intent.setDataAndType(uri, "image/*");
    intent.putExtra("crop", "true");
    intent.putExtra("aspectX", 2);
    intent.putExtra("aspectY", 1);
    intent.putExtra("outputX", outputX);
    intent.putExtra("outputY", outputY);
    intent.putExtra("scale", true);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
    intent.putExtra("return-data", false);
    intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
    intent.putExtra("noFaceDetection", true); // no face detection
    startActivityForResult(intent, requestCode);
}

4:处理返回的data数据

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE_PHOTO && data != null) {
            imageUri = data.getData();
            if (imageUri != null) {//相册选择
                 //todo
            } else {//拍照选择,不能设置MediaStore.EXTRA_OUTPUT
                Bundle extras = data.getExtras();
                //todo
            }
        } else if (resultCode == RESULT_OK && requestCode == REQUEST_CODE_CAMERA && imageUri != null) {//拍照选择,设置MediaStore.EXTRA_OUTPUT
              //todo
        } else if (resultCode == RESULT_OK && requestCode == 130 && imageUri != null) {//拍照选择,设置MediaStore.EXTRA_OUTPUT
           //todo
        }
    }

5:从uri中获取bitmap对象

private Bitmap getImage(Uri imageUri) {
  return MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
 }

6:从uri中获取path路径

 public static String getPathFromUri(@NonNull Context context, @NonNull Uri uri) {
     String path = "";
     if (uri.getScheme().equalsIgnoreCase(ContentResolver.SCHEME_CONTENT)) {
         Cursor cursor;
         final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
         if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
             String wholeID = DocumentsContract.getDocumentId(uri);
             String id = wholeID.split(":")[1];
             String[] column = {MediaStore.Images.Media.DATA};
             String sel = MediaStore.Images.Media._ID + "=?";
             cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, column,
                     sel, new String[]{id}, null);
             int columnIndex = cursor.getColumnIndex(column[0]);
             if (cursor.moveToFirst()) {
                 path = cursor.getString(columnIndex);
             }
             cursor.close();
         } else {
             String[] projection = {MediaStore.Images.Media.DATA};
             cursor = context.getContentResolver().query(uri, projection, null, null, null);
             int column_index = cursor.getColumnIndexOrThrow(projection[0]);
             cursor.moveToFirst();
             path = cursor.getString(column_index);
             cursor.close();
         }
     } else if (uri.getScheme().equalsIgnoreCase(ContentResolver.SCHEME_FILE)) {
         path = uri.getPath();
     }
     return path;
 }

7:图片压缩,缩放

/**
 * scale image
 *
 * @param org
 * @param newWidth
 * @param newHeight
 * @return
 */
public static Bitmap scaleImageTo(Bitmap org, int newWidth, int newHeight) {
    float scaleWidth = (float) newWidth / org.getWidth();
    float scaleHeight = (float) newHeight / org.getHeight();
    float scale = Math.max(scaleWidth, scaleHeight);
    return scaleImage(org, scale, scale);
}

/**
 * scale image
 *
 * @param org
 * @param scaleWidth  sacle of width
 * @param scaleHeight scale of height
 * @return
 */
public static Bitmap scaleImage(Bitmap org, float scaleWidth, float scaleHeight) {
    if (org == null) {
        return null;
    }
    Matrix matrix = new Matrix();
    matrix.postScale(scaleWidth, scaleHeight);
    return Bitmap.createBitmap(org, 0, 0, org.getWidth(), org.getHeight(), matrix, true);
}

public static int calculateInSampleSize(BitmapFactory.Options options,
                                        int reqWidth, int reqHeight) {
    // 源图片的高度和宽度
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;
    if (height > reqHeight || width > reqWidth) {
        // 计算出实际宽高和目标宽高的比率
        final int heightRatio = Math.round((float) height / (float) reqHeight);
        final int widthRatio = Math.round((float) width / (float) reqWidth);
        // 选择宽和高中最小的比率作为inSampleSize的值,这样可以保证最终图片的宽和高
        // 一定都会大于等于目标的宽和高。
        inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
    }
    return inSampleSize;
}

public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
                                                     int reqWidth, int reqHeight) {
    // 第一次解析将inJustDecodeBounds设置为true,来获取图片大小
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    // 调用上面定义的方法计算inSampleSize值
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
    // 使用获取到的inSampleSize值再次解析图片
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resId, options);
}

源码: https://github.com/angcyo/PhotoGetDemo


至此: 文章就结束了,如有疑问: QQ群 Android:274306954 欢迎您的加入.

©️2020 CSDN 皮肤主题: 猿与汪的秘密 设计师: 上身试试 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值