# SelectPicAndCamera **Repository Path**: forezp/SelectPicAndCamera ## Basic Information - **Project Name**: SelectPicAndCamera - **Description**: No description available - **Primary Language**: Java - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2018-06-28 - **Last Updated**: 2020-12-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # SelectPicAndCamera 最近做项目需要用到拍照和选择相册照片,并显示出来imageview 上,然后压缩上传到服务器中,这本是一个非常常见的功能,但对于图片的处理确实一个技术活,稍微不注意会出现oom,图片压缩也要处理的刚刚好,不能浪费用户的流量,也不能过分的压缩使图片失真,这真的不简单,好在开源中国的安卓端app以开源,本人特意从开源中国整理了这个demo,分享给大家。 进入相册选择照片:注意6.0之后要申请运行时权限,即api23。 ```java Intent intent; if (Build.VERSION.SDK_INT < 19) { intent = new Intent(); intent.setAction(Intent.ACTION_GET_CONTENT); intent.setType("image/*"); startActivityForResult(Intent.createChooser(intent, "选择图片"), ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD); } else { intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); intent.setType("image/*"); startActivityForResult(Intent.createChooser(intent, "选择图片"), ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD); } ``` 或者拍照: ``` private void toCamera() { // 判断是否挂载了SD卡 String savePath = ""; String storageState = Environment.getExternalStorageState(); if (storageState.equals(Environment.MEDIA_MOUNTED)) { savePath = Environment.getExternalStorageDirectory() .getAbsolutePath() + "/oschina/Camera/"; File savedir = new File(savePath); if (!savedir.exists()) { savedir.mkdirs(); } } // 没有挂载SD卡,无法保存文件 if (TextUtils.isEmpty(savePath)) { // AppContext.showToastShort("无法保存照片,请检查SD卡是否挂载"); return; } String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); String fileName = timeStamp + ".jpg";// 照片命名 File out = new File(savePath, fileName); Uri uri = Uri.fromFile(out); //tweet.setImageFilePath(savePath + fileName); // 该照片的绝对路径 mPhotoPath=savePath + fileName; Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); startActivityForResult(intent, ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA); } ``` 在onActivity获取图片信息: ``` @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode != Activity.RESULT_OK) return; if (requestCode == ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD) { if (data == null) return; Uri selectedImageUri = data.getData(); if (selectedImageUri != null) { String path = ImageUtils.getImagePath(selectedImageUri, this); setImageFromPath(path); } } else if (requestCode == ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA) { //setImageFromPath(tweet.getImageFilePath()); setImageFromPath(mPhotoPath); } } ``` 通过返回的uri获取图片路径 ``` /** * 通过Uri获取文件路径 * 支持图片媒体,文件等 *
* Author qiujuer@live.cn * * @param uri Uri * @param context Context * @return 文件路径 */ @SuppressLint({"NewApi", "Recycle"}) public static String getImagePath(Uri uri, Context context) { String selection = null; String[] selectionArgs = null; // Uri is different in versions after KITKAT (Android 4.4), we need to if (Build.VERSION.SDK_INT >= 19 && DocumentsContract.isDocumentUri(context.getApplicationContext(), uri)) { String authority = uri.getAuthority(); if ("com.android.externalstorage.documents".equals(authority)) { // isExternalStorageDocument final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); return Environment.getExternalStorageDirectory() + "/" + split[1]; } else if ("com.android.providers.downloads.documents".equals(authority)) { // isDownloadsDocument final String id = DocumentsContract.getDocumentId(uri); uri = ContentUris.withAppendedId( Uri.parse("content://downloads/public_downloads"), Long.valueOf(id)); } else if ("com.android.providers.media.documents".equals(authority)) { // isMediaDocument final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; if ("image".equals(type)) { uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; } else if ("video".equals(type)) { uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; } else if ("audio".equals(type)) { uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; } selection = "_id=?"; selectionArgs = new String[]{ split[1] }; } } if ("content".equalsIgnoreCase(uri.getScheme())) { String[] projection = {MediaStore.Images.Media.DATA}; Cursor cursor = null; try { cursor = context.getContentResolver() .query(uri, projection, selection, selectionArgs, null); if (cursor != null) { int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); if (cursor.moveToFirst()) { return cursor.getString(column_index); } } } catch (Exception e) { e.fillInStackTrace(); } finally { if (cursor != null) cursor.close(); } } else if ("file".equalsIgnoreCase(uri.getScheme())) { return uri.getPath(); } return null; } ``` 根据图片地址去获取bitmap这时需要自己传入图片的大小即高度和宽度,根据自己的需求去传。 ``` Bitmap bitmap = BitmapCreate.bitmapFromStream(new FileInputStream(path), 512, 512); ``` 图片压缩 ``` /** * 获取一个指定大小的bitmap