Advertisement
Guest User

Untitled

a guest
May 27th, 2016
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.11 KB | None | 0 0
  1. //MIT License
  2. //Copyright (c) 2015 Karol Wrótniak, Droids On Roids
  3. package pl.droidsonroids.imagehelpers;
  4.  
  5. import java.io.File;
  6. import java.util.regex.Matcher;
  7. import java.util.regex.Pattern;
  8. import android.app.Activity;
  9. import android.content.ActivityNotFoundException;
  10. import android.content.ContentResolver;
  11. import android.content.ContentValues;
  12. import android.content.Context;
  13. import android.content.Intent;
  14. import android.content.SharedPreferences;
  15. import android.database.Cursor;
  16. import android.net.Uri;
  17. import android.os.Environment;
  18. import android.provider.MediaStore;
  19. import android.provider.MediaStore.Images.ImageColumns;
  20. import android.provider.MediaStore.MediaColumns;
  21.  
  22. /**
  23. * Helper for sending ACTION_IMAGE_CAPTURE intent and retrieve its results. Handles all low level operations
  24. * <br>
  25. * Usage:<br>
  26. * <ol>
  27. * <li>Launch camera app by calling {@link #launchCameraApp(int, Activity, String)}, save resulting Uri, handle (or ignore) exceptions.</li>
  28. * <li>In your onActivityResult(int requestCode, int resultCode, Intent data) call {@link #retrievePhotoResult(Activity, String) ) }. You may want to inform user if photo cannot be read despite the result is RESULT_OK.</li>
  29. * </ol>
  30. * @author koral--
  31. *
  32. */
  33. public class ImageCaptureHelper
  34. {
  35. private ImageCaptureHelper ()
  36. {}
  37.  
  38. private static final String[] PROJECTION = new String[] { MediaColumns.DATA };
  39. private static final ContentValues CONTENT_VALUES = new ContentValues( 1 );
  40. private static final String PHOTO_SHARED_PREFS_NAME = "photo_shared";
  41. private static final String PHOTO_URI = "photo_uri";
  42. /**
  43. * Description text inserted into @link{ImageColumns.DESCRIPTION} column
  44. */
  45. public static final String DESCRIPTION="Photo taken with example application" ;
  46. static
  47. {
  48. CONTENT_VALUES.put( ImageColumns.DESCRIPTION, DESCRIPTION);
  49. }
  50. /**
  51. * Tries to obtain File containing taken photo. Perform cleanups if photo was not taken or it is empty.
  52. * @param caller caller Activity
  53. * @param photoKey key in Shared Preferences for taken image, can be null
  54. * @return File containing photo or null if no or empty photo was saved by camera app.
  55. */
  56. public static File retrievePhotoResult ( Activity caller, String photoKey )
  57. {
  58. try
  59. {
  60. if ( photoKey == null )
  61. {
  62. photoKey = PHOTO_URI;
  63. }
  64. SharedPreferences prefs = caller.getSharedPreferences( PHOTO_SHARED_PREFS_NAME, Context.MODE_PRIVATE );
  65. String takenPhotoUriString = prefs.getString( photoKey, null );
  66. prefs.edit().remove( photoKey ).commit();
  67.  
  68. if ( takenPhotoUriString == null )
  69. {
  70. return null;
  71. }
  72.  
  73. Uri takenPhotoUri = Uri.parse( takenPhotoUriString );
  74. ContentResolver cr = caller.getContentResolver();
  75. File out = new File( getPhotoFilePath( takenPhotoUri, cr ) );
  76. if ( !out.isFile() || ( out.length() == 0 ) )
  77. {
  78. cr.delete( takenPhotoUri, null, null );
  79. }
  80. else
  81. {
  82. return out;
  83. }
  84. }
  85. catch ( Exception ex )
  86. {
  87. // no-op
  88. }
  89. return null;
  90. }
  91.  
  92. /**
  93. * Tries to create photo placeholder and launch camera app
  94. * @param requestCode your unique code that will be returned in onActivityResult
  95. * @param caller caller Activity
  96. * @param photoKey key in Shared Preferences for taken image, can be null
  97. * @throws ActivityNotFoundException if no camera app was found
  98. * @throws Exception if there is a problem with create photo eg. SDcard is not mounted. It may be eg. {@link IllegalStateException} or {@link UnsupportedOperationException} depending on {@link ContentResolver}.
  99. */
  100. public static void launchCameraApp ( int requestCode, Activity caller, String photoKey ) throws ActivityNotFoundException, Exception
  101. {
  102. if ( photoKey == null )
  103. {
  104. photoKey = PHOTO_URI;
  105. }
  106.  
  107. ContentResolver cr = caller.getContentResolver();
  108. Uri takenPhotoUri = cr.insert( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, CONTENT_VALUES );
  109. if ( takenPhotoUri == null )
  110. {
  111. throw new IllegalStateException( "Photo insertion failed" );
  112. }
  113. Intent intent = new Intent( MediaStore.ACTION_IMAGE_CAPTURE );
  114. intent.putExtra( MediaStore.EXTRA_OUTPUT, getIntentUri( takenPhotoUri, cr ) );
  115. caller.startActivityForResult( intent, requestCode );
  116.  
  117. SharedPreferences prefs = caller.getSharedPreferences( PHOTO_SHARED_PREFS_NAME, Context.MODE_PRIVATE );
  118.  
  119. prefs.edit().putString( photoKey, takenPhotoUri.toString() ).commit();
  120. }
  121.  
  122. private static Uri getIntentUri ( Uri takenPhotoUri, ContentResolver cr )
  123. {
  124. String path = getPhotoFilePath( takenPhotoUri, cr );
  125. if ( path == null )
  126. {
  127. throw new IllegalStateException( "Photo resolution failed" );
  128. }
  129. return Uri.fromFile( new File( path ) );
  130. }
  131.  
  132. private static String getPhotoFilePath ( Uri takenPhotoUri, ContentResolver cr )
  133. {
  134. Cursor cursor = cr.query( takenPhotoUri, PROJECTION, null, null, null );
  135. String res = null;
  136. if ( cursor != null )
  137. {
  138. int dataIdx = cursor.getColumnIndex( MediaColumns.DATA );
  139. if (dataIdx>=0&&cursor.moveToFirst())
  140. res = cursor.getString( dataIdx );
  141. cursor.close();
  142. }
  143. return res;
  144. }
  145.  
  146. /**
  147. * Dirty hack for API level <8 to get a top-level public external storage directory where Camera photos should be placed.<br>
  148. * Empty photo is inserted, path of its parent directory is retrieved and then photo is deleted.<br>
  149. * If photo cannot be inserted eg. external storage is not mounted, then "DCIM" folder in root of the external storage is used as a fallback.
  150. * @param cr {@link ContentResolver} used to resolve image Uris
  151. * @return path to directory where camera app places photos (may be fallback)
  152. */
  153. public static String getPhotoDirPath(ContentResolver cr)
  154. {
  155. String fallback=Environment.getExternalStorageDirectory()+"/DCIM";
  156. Uri takenPhotoUri =null;
  157. String photoFilePath=null;
  158. try
  159. {
  160. takenPhotoUri=cr.insert( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, CONTENT_VALUES );
  161. if ( takenPhotoUri == null )
  162. return fallback;
  163. photoFilePath=getPhotoFilePath( takenPhotoUri, cr );
  164. cr.delete( takenPhotoUri, null, null );
  165. }
  166. catch (Exception ex)
  167. {
  168. //igonred
  169. }
  170. if (photoFilePath==null)
  171. return fallback;
  172. String parent = new File(photoFilePath).getParent();
  173. Matcher m = Pattern.compile( "/DCIM(/|$)").matcher( parent );
  174. if (m.find())
  175. parent= parent.substring( 0, m.end() );
  176.  
  177. return parent;
  178. }
  179. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement