这个功能借鉴了多个大神的,然后整合起来。
Android中相机拍摄照片,以及相册选择图片压缩上传(压缩后保存进SD中)(可用 于修改头像等)
第一步:
private int CAPTURE_CODE = 0; private int IMAGE_CODE = 2;
public void onClick(View v) { switch (v.getId()) { case R.id.btn_photo_album: //打开相册 Intent intent_photo = new Intent(Intent.ACTION_GET_CONTENT); intent_photo.setType("image/*"); startActivityForResult(intent_photo, IMAGE_CODE); break; case R.id.btn_carmen: //打开相机 //用当前时间给取得的图片命名 Intent intent_carmen = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent_carmen.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); // 判断存储卡是否可以用,可用进行存储 SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA); //根据当前时间生成图片的名称 PHOTO_FILE_NAME = "/" + formatter.format(new Date()) + ".jpg"; //判断sd是否存在 if (SDCardUtils.isSDCardEnable()) { intent_carmen.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment .getExternalStorageDirectory(), PHOTO_FILE_NAME))); } startActivityForResult(intent_carmen, CAPTURE_CODE); break; default: break; } }
第二步:
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { /** * 相册和相机result */ int PHOTO_REQUEST_CUT = 3; if (requestCode == IMAGE_CODE) {//相册 PHOTO_REQUEST_GALLERY if (data != null) { // 得到图片的全路径 Uri uri = data.getData(); //将获取的图片uri转为filePath String filePath = GetPathUtil.getPath(this, uri); try { //压缩图片 Bitmap bitmap = BitmapUtils.compressBySize(filePath); //保存图片 FileUtil.saveFile(bitmap, SAVE_FILE_PATH); } catch (Exception e) { e.printStackTrace(); } //开始上传(SAVE_FILE_PATH,这个地址就可以直接用了,是压缩后的图片地址) } } else if (requestCode == CAPTURE_CODE) {//相机 PHOTO_REQUEST_CAMERA if (SDCardUtils.isSDCardEnable()) { File tempFile = new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME); try { //压缩图片 Bitmap bitmap = BitmapUtils.compressBySize(tempFile.getAbsolutePath()); //保存图片 FileUtil.saveFile(bitmap, SAVE_FILE_PATH); } catch (Exception e) { e.printStackTrace(); } //开始上传(SAVE_FILE_PATH,这个地址就可以直接用了,是压缩后的图片地址) } else { showToast("未找到存储卡,无法存储照片!"); } } else if (requestCode == PHOTO_REQUEST_CUT) { //图片剪裁完成 } super.onActivityResult(requestCode, resultCode, data); }
第三步(将uri转为图片地址,压缩图片,保存压缩后的图片到sd卡的方法):
1.将uri转为图片地址的方法:
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]; } // TODO handle non-primary volumes } // 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 getDataColumn(context, uri, null, null); } // File else if ("file".equalsIgnoreCase(uri.getScheme())) { return uri.getPath(); } return null; }
2.压缩图片的方法:
//压缩图片尺寸 public static Bitmap compressBySize(String pathName) { BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inJustDecodeBounds = true;// 不去真的解析图片,只是获取图片的头部信息,包含宽高等; Bitmap bitmap = BitmapFactory.decodeFile(pathName, opts); // 得到图片的宽度、高度; float imgWidth = opts.outWidth; float imgHeight = opts.outHeight; // 分别计算图片宽度、高度与目标宽度、高度的比例;取大于等于该比例的最小整数; int widthRatio = (int) Math.ceil(imgWidth / (float) 300); int heightRatio = (int) Math.ceil(imgHeight / (float) 300); opts.inSampleSize = 1; if (widthRatio > 1 || widthRatio > 1) { if (widthRatio > heightRatio) { opts.inSampleSize = widthRatio; } else { opts.inSampleSize = heightRatio; } } //设置好缩放比例后,加载图片进内容; opts.inJustDecodeBounds = false; bitmap = BitmapFactory.decodeFile(pathName, opts); return bitmap; }
3.保存压缩后的图片到sd卡的方法:
//存储进SD卡 public static void saveFile(Bitmap bm, String fileName) throws Exception { // File dirFile = new File(fileName); // //检测图片是否存在 // if (dirFile.exists()) { // dirFile.delete(); //删除原图片 // } File myCaptureFile = new File(fileName); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile)); //100表示不进行压缩,70表示压缩率为30% bm.compress(Bitmap.CompressFormat.JPEG, 100, bos); bos.flush(); bos.close(); }