Skip to content

Instantly share code, notes, and snippets.

@skylee91
Forked from Mariovc/ ImagePicker.java
Created September 25, 2015 05:54
Show Gist options
  • Select an option

  • Save skylee91/ab7b6d465ef1a6868403 to your computer and use it in GitHub Desktop.

Select an option

Save skylee91/ab7b6d465ef1a6868403 to your computer and use it in GitHub Desktop.
Utility for picking an image from Gallery/Camera with Android Intents
/**
* Author: Mario Velasco Casquero
* Date: 08/09/2015
* Email: [email protected]
*/
public class ImagePicker {
private static final int DEFAULT_MIN_WIDTH_QUALITY = 400; // min pixels
private static final String TAG = "ImagePicker";
private static final String TEMP_IMAGE_NAME = "tempImage";
public static int minWidthQuality = DEFAULT_MIN_WIDTH_QUALITY;
public static Intent getPickImageIntent(Context context) {
Intent chooserIntent = null;
List<Intent> intentList = new ArrayList<>();
Intent pickIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePhotoIntent.putExtra("return-data", true);
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempFile(context)));
intentList = addIntentsToList(context, intentList, pickIntent);
intentList = addIntentsToList(context, intentList, takePhotoIntent);
if (intentList.size() > 0) {
chooserIntent = Intent.createChooser(intentList.remove(intentList.size() -1),
context.getString(R.string.pick_image_intent_text));
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentList.toArray(new Parcelable[]{}));
}
return chooserIntent;
}
private static List<Intent> addIntentsToList(Context context, List<Intent> list, Intent intent) {
List<ResolveInfo> resInfo = context.getPackageManager().queryIntentActivities(intent, 0);
for (ResolveInfo resolveInfo : resInfo) {
String packageName = resolveInfo.activityInfo.packageName;
Intent targetedIntent = new Intent(intent);
targetedIntent.setPackage(packageName);
list.add(targetedIntent);
Log.d(TAG, "Intent: " + intent.getAction() + " package: " + packageName);
}
return list;
}
public static Bitmap getImageFromResult(Context context, int resultCode,
Intent imageReturnedIntent) {
Log.d(TAG, "getImageFromResult, resultCode: " + resultCode);
Bitmap bm = null;
File imageFile = getTempFile(context);
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage;
if (imageReturnedIntent == null) { /** CAMERA **/
selectedImage = Uri.fromFile(imageFile);
} else { /** ALBUM **/
selectedImage = imageReturnedIntent.getData();
}
Log.d(TAG, "selectedImage: " + selectedImage);
bm = getImageResized(context, selectedImage);
if (isCamera) {
bm = rotateIfNeeded(context, bm, imageFile);
}
}
return bm;
}
private static File getTempFile(Context context) {
File imageFile = new File(context.getExternalCacheDir(), TEMP_IMAGE_NAME);
imageFile.getParentFile().mkdirs();
return imageFile;
}
private static Bitmap decodeBitmap(Context context, Uri theUri, int sampleSize) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = sampleSize;
AssetFileDescriptor fileDescriptor = null;
try {
fileDescriptor = context.getContentResolver().openAssetFileDescriptor(theUri, "r");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap actuallyUsableBitmap = BitmapFactory.decodeFileDescriptor(
fileDescriptor.getFileDescriptor(), null, options);
Log.d(TAG, options.inSampleSize + " sample method bitmap ... " +
actuallyUsableBitmap.getWidth() + " " + actuallyUsableBitmap.getHeight());
return actuallyUsableBitmap;
}
private static Bitmap getImageResized(Context context, Uri selectedImage) {
Bitmap bm = null;
int sampleSize = 7; // TODO improve resizer
do {
sampleSize -= 2;
bm = decodeBitmap(context, selectedImage, sampleSize);
Log.d(TAG, "resizer: new bitmap width = " + bm.getWidth());
} while (bm.getWidth() < minWidthQuality && sampleSize > 1);
return bm;
}
private static Bitmap rotateIfNeeded(Context context, Bitmap bm, File imageFile) {
int rot = getCameraPhotoOrientation(context, imageFile);
if (rot != 0) {
bm = new RotateOrientation().RotateOrientationCall(bm, rot);
}
// saveBitmap(imageFile, bm);
return bm;
}
// private static void saveBitmap(File imageFile, Bitmap bm) {
// Log.d(TAG, "Saving image ... ");
// imageFile.getParentFile().mkdirs();
// FileOutputStream out = null;
// try {
// out = new FileOutputStream(imageFile);
// bm.compress(Bitmap.CompressFormat.PNG, 90, out);
// } catch (Exception e) {
// e.printStackTrace();
// } finally {
// try {
// if (out != null) {
// out.close();
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// Log.d(TAG, "Image saved");
// }
private static int getCameraPhotoOrientation(Context context, File imageFile) {
int rotate = 0;
try {
context.getContentResolver().notifyChange(Uri.fromFile(imageFile), null);
ExifInterface exif = new ExifInterface(imageFile.getAbsolutePath());
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
}
Log.d(TAG, "Exit orientation: " + orientation);
} catch (Exception e) {
e.printStackTrace();
}
return rotate;
}
private static class RotateOrientation {
Bitmap RotateOrientationCall(Bitmap src, float degree) {
Matrix matrix = new Matrix();
matrix.postRotate(degree);
Bitmap bmOut = Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), matrix, true);
return bmOut;
}
}
}
public class SimpleActivity {
private static final int PICK_IMAGE_ID = 234; // the number doesn't matter
public void onPickImage(View view) {
Intent chooseImageIntent = ImagePicker.getPickImageIntent(this);
startActivityForResult(chooseImageIntent, PICK_IMAGE_ID);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode) {
case PICK_IMAGE_ID:
Bitmap bitmap = ImagePicker.getImageFromResult(this, resultCode, data);
// TODO use bitmap
break;
default:
super.onActivityResult(requestCode, resultCode, data);
break;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment