Advertisement
Guest User

Untitled

a guest
Jun 23rd, 2017
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.53 KB | None | 0 0
  1. package com.theartofdev.cropcameraimage;
  2.  
  3. import android.Manifest;
  4. import android.app.Activity;
  5. import android.content.ComponentName;
  6. import android.content.ContentResolver;
  7. import android.content.ContentUris;
  8. import android.content.Context;
  9. import android.content.Intent;
  10. import android.content.pm.PackageManager;
  11. import android.content.pm.ResolveInfo;
  12. import android.database.Cursor;
  13. import android.graphics.Bitmap;
  14. import android.net.Uri;
  15. import android.os.Build;
  16. import android.os.Bundle;
  17. import android.os.Environment;
  18. import android.os.Parcelable;
  19. import android.provider.DocumentsContract;
  20. import android.provider.MediaStore;
  21. import android.system.ErrnoException;
  22. import android.support.v7.app.ActionBarActivity;
  23. import android.util.Log;
  24. import android.view.View;
  25. import android.widget.Toast;
  26.  
  27. import com.theartofdev.edmodo.cropper.CropImageView;
  28.  
  29. import java.io.File;
  30. import java.io.FileInputStream;
  31. import java.io.FileNotFoundException;
  32. import java.io.InputStream;
  33. import java.util.ArrayList;
  34. import java.util.List;
  35.  
  36. public class MainActivity extends ActionBarActivity {
  37.  
  38. private CropImageView mCropImageView;
  39.  
  40. private Uri mCropImageUri;
  41.  
  42. @Override
  43. protected void onCreate(Bundle savedInstanceState) {
  44. super.onCreate(savedInstanceState);
  45. setContentView(R.layout.main_activity);
  46. mCropImageView = (CropImageView) findViewById(R.id.CropImageView);
  47. }
  48.  
  49. /**
  50. * On load image button click, start pick image chooser activity.
  51. */
  52. public void onLoadImageClick(View view) {
  53. startActivityForResult(getPickImageChooserIntent(), 200);
  54. }
  55.  
  56. /**
  57. * Crop the image and set it back to the cropping view.
  58. */
  59. public void onCropImageClick(View view) {
  60. Bitmap cropped = mCropImageView.getCroppedImage(500, 500);
  61. if (cropped != null)
  62. mCropImageView.setImageBitmap(cropped);
  63. }
  64.  
  65. @Override
  66. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  67. if (resultCode == Activity.RESULT_OK) {
  68. Uri imageUri = getPickImageResultUri(data);
  69.  
  70. // For API >= 23 we need to check specifically that we have permissions to read external storage,
  71. // but we don't know if we need to for the URI so the simplest is to try open the stream and see if we get error.
  72. boolean requirePermissions = false;
  73. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
  74. checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED &&
  75. isUriRequiresPermissions(imageUri)) {
  76.  
  77. // request permissions and handle the result in onRequestPermissionsResult()
  78. requirePermissions = true;
  79. mCropImageUri = imageUri;
  80. requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
  81. }
  82.  
  83. if (!requirePermissions) {
  84. android.util.Log.i("CHEOK", "imageUri is " + imageUri);
  85. android.util.Log.i("CHEOK", "getPath(context, imageUri) is " + getPath(this, imageUri));
  86. try {
  87. android.util.Log.i("CHEOK", "Is file exists -> " + new File(getPath(this, imageUri)).exists());
  88.  
  89. new FileInputStream(getPath(this, imageUri));
  90. android.util.Log.i("CHEOK", "Can new FileInputStream");
  91. } catch (FileNotFoundException e) {
  92. android.util.Log.i("CHEOK", "XXXX " + e);
  93. e.printStackTrace();
  94. }
  95.  
  96. mCropImageView.setImageUriAsync(imageUri);
  97. }
  98. }
  99. }
  100.  
  101.  
  102. public static String getPath(final Context context, final Uri uri) {
  103.  
  104. final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
  105.  
  106. Log.i("CHEOK", "getPath -1");
  107. // DocumentProvider
  108. if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
  109. Log.i("CHEOK", "getPath 0");
  110. // ExternalStorageProvider
  111. if (isExternalStorageDocument(uri)) {
  112. Log.i("CHEOK", "getPath 1");
  113. final String docId = DocumentsContract.getDocumentId(uri);
  114. final String[] split = docId.split(":");
  115. final String type = split[0];
  116.  
  117. if ("primary".equalsIgnoreCase(type)) {
  118. Log.i("CHEOK", "getPath 2");
  119. return Environment.getExternalStorageDirectory() + "/" + split[1];
  120. }
  121.  
  122. // TODO handle non-primary volumes
  123. }
  124. // DownloadsProvider
  125. else if (isDownloadsDocument(uri)) {
  126. Log.i("CHEOK", "getPath 3");
  127. final String id = DocumentsContract.getDocumentId(uri);
  128. Long idAsLong = null;
  129. try {
  130. idAsLong = Long.valueOf(id);
  131. } catch (NumberFormatException e) {
  132. Log.e("CHEOK", "", e);
  133. // ???
  134. return null;
  135. }
  136. final Uri contentUri = ContentUris.withAppendedId(
  137. Uri.parse("content://downloads/public_downloads"), idAsLong);
  138.  
  139. Log.i("CHEOK", "getPath 4");
  140. return getDataColumn(context, contentUri, null, null);
  141. }
  142. // MediaProvider
  143. else if (isMediaDocument(uri)) {
  144. Log.i("CHEOK", "getPath 5");
  145. final String docId = DocumentsContract.getDocumentId(uri);
  146. final String[] split = docId.split(":");
  147. final String type = split[0];
  148.  
  149. Uri contentUri = null;
  150. if ("image".equals(type)) {
  151. contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
  152. } else if ("video".equals(type)) {
  153. contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
  154. } else if ("audio".equals(type)) {
  155. contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
  156. }
  157.  
  158. final String selection = "_id=?";
  159. final String[] selectionArgs = new String[] {
  160. split[1]
  161. };
  162.  
  163. Log.i("CHEOK", "getPath 6");
  164. return getDataColumn(context, contentUri, selection, selectionArgs);
  165. }
  166. }
  167. // MediaStore (and general)
  168. else if ("content".equalsIgnoreCase(uri.getScheme())) {
  169. Log.i("CHEOK", "getPath 7");
  170. // Return the remote address
  171. if (isGooglePhotosUri(uri))
  172. return uri.getLastPathSegment();
  173.  
  174. Log.i("CHEOK", "getPath 8");
  175. return getDataColumn(context, uri, null, null);
  176. }
  177. // File
  178. else if ("file".equalsIgnoreCase(uri.getScheme())) {
  179. Log.i("CHEOK", "getPath 9");
  180. return uri.getPath();
  181. }
  182.  
  183. Log.i("CHEOK", "getPath 10");
  184. return null;
  185. }
  186.  
  187. /**
  188. * Get the value of the data column for this Uri. This is useful for
  189. * MediaStore Uris, and other file-based ContentProviders.
  190. *
  191. * @param context The context.
  192. * @param uri The Uri to query.
  193. * @param selection (Optional) Filter used in the query.
  194. * @param selectionArgs (Optional) Selection arguments used in the query.
  195. * @return The value of the _data column, which is typically a file path.
  196. */
  197. public static String getDataColumn(Context context, Uri uri, String selection,
  198. String[] selectionArgs) {
  199.  
  200. Cursor cursor = null;
  201. final String column = "_data";
  202. final String[] projection = {
  203. column
  204. };
  205.  
  206. try {
  207. cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
  208. null);
  209. if (cursor != null && cursor.moveToFirst()) {
  210. final int index = cursor.getColumnIndexOrThrow(column);
  211. return cursor.getString(index);
  212. }
  213. } catch (java.lang.IllegalArgumentException e) {
  214. Log.e("CHEOK", "", e);
  215. } finally {
  216. if (cursor != null)
  217. cursor.close();
  218. }
  219. return null;
  220. }
  221.  
  222.  
  223. /**
  224. * @param uri The Uri to check.
  225. * @return Whether the Uri authority is ExternalStorageProvider.
  226. */
  227. public static boolean isExternalStorageDocument(Uri uri) {
  228. return "com.android.externalstorage.documents".equals(uri.getAuthority());
  229. }
  230.  
  231. /**
  232. * @param uri The Uri to check.
  233. * @return Whether the Uri authority is DownloadsProvider.
  234. */
  235. public static boolean isDownloadsDocument(Uri uri) {
  236. return "com.android.providers.downloads.documents".equals(uri.getAuthority());
  237. }
  238.  
  239. /**
  240. * @param uri The Uri to check.
  241. * @return Whether the Uri authority is MediaProvider.
  242. */
  243. public static boolean isMediaDocument(Uri uri) {
  244. return "com.android.providers.media.documents".equals(uri.getAuthority());
  245. }
  246.  
  247. /**
  248. * @param uri The Uri to check.
  249. * @return Whether the Uri authority is Google Photos.
  250. */
  251. public static boolean isGooglePhotosUri(Uri uri) {
  252. return "com.google.android.apps.photos.content".equals(uri.getAuthority());
  253. }
  254.  
  255.  
  256. @Override
  257. public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
  258. if (mCropImageUri != null && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  259. mCropImageView.setImageUriAsync(mCropImageUri);
  260. } else {
  261. Toast.makeText(this, "Required permissions are not granted", Toast.LENGTH_LONG).show();
  262. }
  263. }
  264.  
  265. /**
  266. * Create a chooser intent to select the source to get image from.<br/>
  267. * The source can be camera's (ACTION_IMAGE_CAPTURE) or gallery's (ACTION_GET_CONTENT).<br/>
  268. * All possible sources are added to the intent chooser.
  269. */
  270. public Intent getPickImageChooserIntent() {
  271.  
  272. // Determine Uri of camera image to save.
  273. Uri outputFileUri = getCaptureImageOutputUri();
  274.  
  275. List<Intent> allIntents = new ArrayList<>();
  276. PackageManager packageManager = getPackageManager();
  277.  
  278. // collect all camera intents
  279. Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
  280. List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
  281. for (ResolveInfo res : listCam) {
  282. Intent intent = new Intent(captureIntent);
  283. intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
  284. intent.setPackage(res.activityInfo.packageName);
  285. if (outputFileUri != null) {
  286. intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
  287. }
  288. allIntents.add(intent);
  289. }
  290.  
  291. // collect all gallery intents
  292. Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
  293. galleryIntent.setType("image/*");
  294. List<ResolveInfo> listGallery = packageManager.queryIntentActivities(galleryIntent, 0);
  295. for (ResolveInfo res : listGallery) {
  296. Intent intent = new Intent(galleryIntent);
  297. intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
  298. intent.setPackage(res.activityInfo.packageName);
  299. allIntents.add(intent);
  300. }
  301.  
  302. // the main intent is the last in the list (fucking android) so pickup the useless one
  303. Intent mainIntent = allIntents.get(allIntents.size() - 1);
  304. for (Intent intent : allIntents) {
  305. if (intent.getComponent().getClassName().equals("com.android.documentsui.DocumentsActivity")) {
  306. mainIntent = intent;
  307. break;
  308. }
  309. }
  310. allIntents.remove(mainIntent);
  311.  
  312. // Create a chooser from the main intent
  313. Intent chooserIntent = Intent.createChooser(mainIntent, "Select source");
  314.  
  315. // Add all other intents
  316. chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, allIntents.toArray(new Parcelable[allIntents.size()]));
  317.  
  318. return chooserIntent;
  319. }
  320.  
  321. /**
  322. * Get URI to image received from capture by camera.
  323. */
  324. private Uri getCaptureImageOutputUri() {
  325. Uri outputFileUri = null;
  326. File getImage = getExternalCacheDir();
  327. if (getImage != null) {
  328. outputFileUri = Uri.fromFile(new File(getImage.getPath(), "pickImageResult.jpeg"));
  329. }
  330. return outputFileUri;
  331. }
  332.  
  333. /**
  334. * Get the URI of the selected image from {@link #getPickImageChooserIntent()}.<br/>
  335. * Will return the correct URI for camera and gallery image.
  336. *
  337. * @param data the returned data of the activity result
  338. */
  339. public Uri getPickImageResultUri(Intent data) {
  340. boolean isCamera = true;
  341. if (data != null && data.getData() != null) {
  342. String action = data.getAction();
  343. isCamera = action != null && action.equals(MediaStore.ACTION_IMAGE_CAPTURE);
  344. }
  345. return isCamera ? getCaptureImageOutputUri() : data.getData();
  346. }
  347.  
  348. /**
  349. * Test if we can open the given Android URI to test if permission required error is thrown.<br>
  350. */
  351. public boolean isUriRequiresPermissions(Uri uri) {
  352. try {
  353. ContentResolver resolver = getContentResolver();
  354. InputStream stream = resolver.openInputStream(uri);
  355. stream.close();
  356. return false;
  357. } catch (FileNotFoundException e) {
  358. if (e.getCause() instanceof ErrnoException) {
  359. return true;
  360. }
  361. } catch (Exception e) {
  362. }
  363. return false;
  364. }
  365. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement