Android 8.0 및 이하 모든 버 전에 적용 되 는 사진 예제
14721 단어 안 드 로 이 드 사진 처리
Manifest 파일 에 provider 설정
안 드 로 이 드:authorities 에 당신 의 패키지 이름 을 적 었 습 니 다.
뒤에서 뛰 어 다 닐 때 사용 하도록 주의 하 세 요.
Android 6.0 이하 에 대해 서 는 사진 촬영 및 파일 읽 기와 쓰기 권한 을 추가 합 니 다.
코드 예제
public class MainActivity extends Activity {
private ImageView mImageView;
private String mPublicPhotoPath;
private static final int REQ_GALLERY = 33;
private static final int REQUEST_CODE_PICK_IMAGE = 22;
private int mWidth;
private int mHeight;
private Uri uri;
private String path;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
mImageView = (ImageView) findViewById(R.id.iv);
findViewById(R.id.takePicture).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//
showTakePicture();
}
});
findViewById(R.id.picture).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//
getImageFromAlbum();
}
});
}
//
private void showTakePicture() {
// , 6.0 ,
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//7.0
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CAMERA)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
}
}else{
startTake();
}
}else{
startTake();
}
}
//
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1) {
for (int i = 0; i < permissions.length; i++) {
if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
if (i == 0){
startTake();
}
} else {
Toast.makeText(this, "" + " " + permissions[i] + " ", Toast.LENGTH_SHORT).show();
}
}
}
}
private void startTake() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
//
File photoFile = null;
try {
photoFile = createPublicImageFile();
} catch (IOException e) {
e.printStackTrace();
}
// Action
if (photoFile != null) {
takePictureIntent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
// flag
takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uri photoURI;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//7.0
photoURI = FileProvider.getUriForFile(this, "com.example.mycamera.fileprovider", photoFile);
}else{
photoURI = Uri.fromFile(photoFile);
}
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQ_GALLERY);
}
}
//
galleryAddPic(mPublicPhotoPath, this);
}
/**
*
*/
public void getImageFromAlbum() {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");//
startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
}
/**
*
* @return
* @throws IOException
*/
private File createPublicImageFile() throws IOException {
File path = null;
if (hasSdcard()) {
path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM);
}
Date date = new Date();
String timeStamp = getTime(date, "yyyyMMdd_HHmmss", Locale.CHINA);
String imageFileName = "Camera/" + "IMG_" + timeStamp + ".jpg";
File image = new File(path, imageFileName);
mPublicPhotoPath = image.getAbsolutePath();
return image;
}
/**
* sdcard
* @return
*/
public static boolean hasSdcard() {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
return true;
} else {
return false;
}
}
/**
*
* @param date
* @param mode
* @param locale
* @return
*/
private String getTime(Date date, String mode, Locale locale) {
SimpleDateFormat format = new SimpleDateFormat(mode, locale);
return format.format(date);
}
/**
*
*/
public static void galleryAddPic(String mPublicPhotoPath, Context context) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(mPublicPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
context.sendBroadcast(mediaScanIntent);
}
/**
*
* @param requestCode
* @param resultCode
* @param data
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// mImageView
mWidth = mImageView.getWidth();
mHeight = mImageView.getHeight();
switch (requestCode) {
//
case REQ_GALLERY:
if (resultCode != Activity.RESULT_OK) return;
uri = Uri.parse(mPublicPhotoPath);
path = uri.getPath();
break;
//
case REQUEST_CODE_PICK_IMAGE:
if (data == null) return;
uri = data.getData();
int sdkVersion = Integer.valueOf(Build.VERSION.SDK);
if (sdkVersion >= 19) { // android.os.Build.VERSION_CODES.KITKAT 19
path = this.uri.getPath();//5.0 Uri.getPath is : /document/image:46 ,5.0
// path_above19:/storage/emulated/0/girl.jpg
path =getPath_above19(this, this.uri);
} else {
path = getFilePath_below19(this, this.uri);
}
break;
}
mImageView.setImageBitmap(getSmallBitmap(path, mWidth, mHeight));
}
/**
* api19 uri
* @param context
* @param uri
* @return
*/
public static String getFilePath_below19(Context context,Uri uri) {
// , : , sdk>19
String[] proj = {MediaStore.Images.Media.DATA};
// android , Android
Cursor cursor = context.getContentResolver().query(uri, proj, null, null, null);
//
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
// , ,
cursor.moveToFirst();
// :/mnt/sdcard/DCIM/Camera/IMG_20180724_032212.jpg
String path = cursor.getString(column_index);
return path;
}
/**
* api19 uri
* @param context
* @param uri
* @return
*/
@TargetApi(Build.VERSION_CODES.KITKAT)
public static String getPath_above19(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];
}
}
// 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 the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {column};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
/**
*
* @param options
* @param reqWidth
* @param reqHeight
* @return
*/
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 = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
/**
* bitmap
* @param filePath
* @return
*/
public static Bitmap getSmallBitmap(String filePath, int reqWidth, int reqHeight) {
final BitmapFactory.Options options = new BitmapFactory.Options();
//
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(filePath, options);
}
}