Using setPictureSize and Camera Parameters - android

I've looked into figuring out how to set the size of a picture, and I stumbled upon CameraParameters and the setPictureSize method associated with it. The problem is, I can't figure out how to use any of these. I don't know what needs to be imported, what object to create, how to use the setPictureSize method, or where to even place that code. I have 2 chunks of code that I feel may be a good place to use setPictureSize. These chunks are:
takePicture = (Button) findViewById(R.id.takePicture);
takePicture.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (name.getText().length() == 0 || experimentInput.getText().length() == 0) {
showDialog(DIALOG_REJECT);
return;
}
ContentValues values = new ContentValues();
imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
time = getTime() ;
startActivityForResult(intent, CAMERA_PIC_REQUESTED);
}
});
and:
public static File convertImageUriToFile (Uri imageUri, Activity activity) {
if (activity == null) Log.d("test", "NULL!");
Cursor cursor = null;
try {
String [] proj={MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID, MediaStore.Images.ImageColumns.ORIENTATION};
cursor = activity.managedQuery( imageUri,
proj, // Which columns to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
int file_ColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
int orientation_ColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.ORIENTATION);
if (cursor.moveToFirst()) {
#SuppressWarnings("unused")
String orientation = cursor.getString(orientation_ColumnIndex);
return new File(cursor.getString(file_ColumnIndex));
}
return null;
} finally {
if (cursor != null) {
cursor.close();
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if(cursor!=null)
{
//HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
//THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
else return null;
}
So, my question is, how do I use setPictureSize and where should I put it? No website, nor the android development guide, nor any other related StackOverflow question was helpful to me.
Editted Code:
public Bitmap getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if(cursor!=null)
{
//HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
//THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
int desiredImageWidth = 100; // pixels
int desiredImageHeight = 100; // pixels
BitmapFactory.Options o = new BitmapFactory.Options();
o.inSampleSize = 2; // will cut the size of the image in half; OPTIONAL
Bitmap newImage = Bitmap.createScaledBitmap(BitmapFactory.decodeFile(cursor.getString(column_index), o),
desiredImageWidth,
desiredImageHeight,
false);
return newImage; //cursor.getString(column_index);
}
else return null;
}

That's used for when you're actually using the camera through a custom View. What you're doing right here is sending an implicit intent to Android to open another Activity that uses the camera to take a picture.
In this case, you can limit the size of your image by using MediaStore.EXTRA_SIZE_LIMIT. If you want to specify the dimensions of the image, than you have to load it from the URI that it was saved to, create a new scaled image, then resave it over the old one.
Once you have the URI of the image (which is from the DATA attribute in the projection), you can resize the image like so:
int desiredImageWidth = 100; // pixels
int desiredImageHeight = 100; // pixels
BitmapFactory.Options o = new BitmapFactory.Options();
o.inSampleSize = 2; // will cut the size of the image in half; OPTIONAL
Bitmap newImage = Bitmap.createScaleBitmap(BitmapFactory.decodeFile(imagePath, o),
desiredImageWidth,
desiredImageHeight,
false);
Then save it over the old one.

Related

How to retrieve the thumbnail rotation

I am creating a sort of 'Gallery' app that is displaying all the images in a grid.
The issue is: that some of the images are not displayed in the right orientation.
Here is the code to retrieve the thumbnails
final String[] projection = { MediaStore.Images.Thumbnails.DATA, MediaStore.Images.Thumbnails.IMAGE_ID };
//query the thumbnails provider
Cursor thumbnailsCursor = context.getContentResolver().query(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, projection, null,
null, null);
if (thumbnailsCursor.moveToFirst()) {
do {
//get the thumbnail path
fullPath = thumbnailsCursor.getString(fullPathColumnIndex);
thumbnailUri = Uri.parse(fullPath);
//add the uri to the list
thumbnailsList.add(thumbnailUri);
} while (thumbnailsCursor.moveToNext());
thumbnailsCursor.close();
Inside the getView() of the BaseAdapter I am using Picasso image loader library to display the thumbnail, but sometimes the orientation is wrong.
Picasso.with(context).load(new File(photoItem.thumbnail.getPath())).noFade().into(holder.photoImageView);
I have tried querying the real photo data and retrieve the orientation but the process is too slow( couple of seconds long) and the displayed images are too large.
Given the ID of the image you can query the MediaStore to get the path to the original image, and then grab the exif for the orientation from there.
This process is quite fast, and usually only takes a few milliseconds.
Cursor cursor =
CustomApplication
.getContext()
.getContentResolver()
.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[] {MediaStore.Images.Media.DATA}, MediaStore.Images.Media._ID + "=?",
new String[] {"" + PHOTO_ID}, null);
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
String fullPath = cursor.getString(0);
cursor.close();
ExifInterface exif = new ExifInterface(fullPath);
int exifOrientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
//ROTATE AND FLIP YOUR THUMBNAIL AS NEEDED BASED ON exifOrientation
}
Here is the correct solution. You can query the orientation data from MediaStore so use
MediaStore.Images.Media.ORIENTATION to get orientation degreee.
final String[] projection = { MediaStore.Images.Thumbnails.DATA, MediaStore.Images.Thumbnails.IMAGE_ID, MediaStore.Images.Media.ORIENTATION };
Cursor thumbnailsCursor = context.getContentResolver().query(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, projection, null, null, null);
if (thumbnailsCursor.moveToFirst()) {
do {
int orientationColumnIndex = thumbnailsCursor.getColumnIndex(MediaStore.Images.Media.ORIENTATION);
int orientation = cur.getInt(orientationColumnIndex);
//do what you want to do with orientation value
}while (thumbnailsCursor.moveToNext());
thumbnailsCursor.close();
will give you the orientation in degrees.
You could use the ExifInterface class as follows:
int originalOrientation = ExifInterface.ORIENTATION_NORMAL;
try {
ExifInterface exif = new ExifInterface(photoItem.thumbnail.getPath().toString());
originalOrientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
} catch (IOException e) {
e.printStackTrace();
}
Then you can check if it is rotated and do whatever logic you need (such as passing in a rotate angle to the Picasso request).
if (originalOrientation == ExifInterface.ORIENTATION_ROTATE_90 || originalOrientation == ExifInterface.ORIENTATION_ROTATE_270) {
//do something
}
This is the method I use and I have never noticed any performance impact.
I have found that you can apply custom transformations for your loading task in picasso lib.
here is solution refer it.
at there transform method is using MATRIX same as other have given ansewer..
i have not checked yet.
public static float getOrientationValue(String location) {
ExifInterface exif = null;
try {
exif = new ExifInterface(new File(location).getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
int rotate = 0;
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_270:
rotate += 90;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate += 90;
case ExifInterface.ORIENTATION_ROTATE_90:
rotate += 90;
}
return rotate;
}
or
public static int getOrientation(Context context, Uri photoUri) {
/* it's on the external media. */
Cursor cursor = context.getContentResolver().query(photoUri,
new String[] { MediaStore.Images.ImageColumns.ORIENTATION }, null, null, null);
if (cursor.getCount() != 1) {
return -1;
}
cursor.moveToFirst();
return cursor.getInt(0);
}

How to get total video & image size from external SD card

I am trying to calculate total memory size (video & image) from external SD card. For example there is a method MediaStore.Audio.Media.getContentUriForPath(String path). From where I can get the URI and calculate the size audio files. By passing ..
private long getMedia(Uri uri) {
Log.e("URI",uri+"");
String[] proj = { MediaStore.MediaColumns.SIZE };
Cursor cursor = ((Activity) context).getContentResolver().query(uri, proj, null, null, null);
long size = DirectoryMediaSize.getMediaSize(cursor);
cursor.close();
return size;
}
There is no such method like MediaStore.Video.Media.getContentUriForPath(). So how can i calculate the size for (video & image) ???
Try below code:-
Uri selectedImageURI = data.getData();
File imageFile = new File(getRealPathFromURI(selectedImageURI));
long check = ((imageFile.length() / 1024));
if (check < 5000)
{
// less then 5 mb
}
else
{
// greater then 5 mb
}
function getRealPathFromURI
String getRealPathFromURI(Uri contentURI)
{
String result;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null)
{ // Source is Dropbox or other similar local file path
result = contentURI.getPath();
}
else
{
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}

select thumbnail from android gallery

I know how to get a photo from gallery in android
Intent gallery = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(gallery, PHOTO_REQUEST_CODE);
But how would I specifically select a thumbnail?
REASON FOR BOUNTY:
I have already tried both solutions at Get thumbnail Uri/path of the image stored in sd card + android . They don't work for me. I don't know how to get selectedImageUri, which is of type long, from data in
onActivityResult(int requestCode, int resultCode, Intent data)
String fn = ...; // file name
ContentResolver cr = ctx.getContentResolver();
Cursor c = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[]{
BaseColumns._ID
}, MediaColumns.DATA + "=?", new String[]{ fn }, null);
if(c!=null) {
try{
if(c.moveToNext()) {
long id = c.getLong(0);
Bitmap thumbnail = MediaStore.Images.Thumbnails.getThumbnail(cr, id, MediaStore.Images.Thumbnails.MINI_KIND, null);
}
}finally{
c.close();
}
}
If you have its cursor in hand, you can get its ID as ,
int id = cursor.getInt(cursor
.getColumnIndex(MediaStore.MediaColumns._ID));
Reffer the following code
Cursor cursor = context.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Images.Media._ID },
MediaStore.Images.Media.DATA + "=? ",
new String[] { filePath }, null);
if (cursor != null && cursor.moveToFirst()) {
int id = cursor.getInt(cursor
.getColumnIndex(MediaStore.MediaColumns._ID));
Uri baseUri = Uri.parse("content://media/external/images/media");
return Uri.withAppendedPath(baseUri, "" + id);
So, for thumbnail,
Bitmap thumbnail = MediaStore.Images.Thumbnails.getThumbnail(cursor, id, MediaStore.Images.Thumbnails.MINI_KIND, null);
Hey so if everything else isn't working for you here is an easy way to make your own thumbnail if you have the Bitmap. If you don't know how to load the Bitmap from the Uri:
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
Here is the code to make a nice formatted thumbnail:
final int THUMBNAIL_HEIGHT = 75;//48
final int THUMBNAIL_WIDTH = 75;//66
Float width = new Float(bitmap.getWidth());
Float height = new Float(bitmap.getHeight());
Float ratio = width/height;
bitmap = Bitmap.createScaledBitmap(bitmap, (int)(THUMBNAIL_HEIGHT*ratio), THUMBNAIL_HEIGHT, false);
int padding = (THUMBNAIL_WIDTH - bitmap.getWidth())/2;
image.setPadding(padding, padding, padding, padding);
image.setBackgroundColor(0);
image.setImageBitmap(bitmap);
In this code "image" is the variable for the ImageView. I hope this helps some :D

Not able to pick photo from gallery?

I am able to open the gallery and getting the path of gallery as=
content://media/external/images/media/2
but not able to decode in imageview
this is my code
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b=(Button) findViewById(R.id.Button01);
b.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// in onCreate or any event where your want the user to
// select a file
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,IMAGE_PICK);
}
});
}
//UPDATED
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == IMAGE_PICK) {
Uri selectedImageUri = data.getData();
//OI FILE Manager
filemanagerstring = selectedImageUri.getPath();
//MEDIA GALLERY
selectedImagePath = getPath(selectedImageUri);
if(selectedImagePath!=null)
{
path = selectedImageUri.toString();
m1.setPath(path);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
Bitmap yourSelectedImage = BitmapFactory.decodeFile(path, options);
ImageButton img2=(ImageButton)findViewById(R.id.widget27);
img2.setImageBitmap(yourSelectedImage);
Toast.makeText(getBaseContext(), path, 1000).show();
}
}
}
}
public String getPath(Uri uri) {
String [] proj={MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(uri,
proj, // Which columns to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}
Please help thanks in advance
This piece of code should be put in your onActivityResult. It gives you the way to decode file path from fetched image URI:
Uri selectedImageUri = data.getData();
String[] projection = { MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(selectedImageUri, projection, null, null, null);
int column_index_data = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
selectedImagePath = cursor.getString(column_index_data);
Bitmap galleryImage = BitmapFactory.decodeFile(selectedImagePath);
We need to do following changes/fixes in our earlier onActivityResult()'s gallery picker code to run seamlessly on Kitkat and on all other earlier versions as well.
Uri selectedImgFileUri = data.getData();
if (selectedImgFileUri == null ) {
// user has not selected any photo
}
try {
InputStream input = mActivity.getContentResolver().openInputStream(selectedImgFileUri);
mSelectedPhotoBmp = BitmapFactory.decodeStream(input);
} catch (Throwable tr) {
// show message to try again
}

android get real path by Uri.getPath()

I'm trying to get image from gallery.
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select picture"), resultCode );
After I returned from this activity I have a data, which contains Uri. It looks like:
content://media/external/images/1
How can I convert this path to real one (just like '/sdcard/image.png') ?
Thanks
This is what I do:
Uri selectedImageURI = data.getData();
imageFile = new File(getRealPathFromURI(selectedImageURI));
and:
private String getRealPathFromURI(Uri contentURI) {
String result;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
NOTE: managedQuery() method is deprecated, so I am not using it.
Last edit: Improvement. We should close cursor!!
Is it really necessary for you to get a physical path?
For example, ImageView.setImageURI() and ContentResolver.openInputStream() allow you to access the contents of a file without knowing its real path.
#Rene Juuse - above in comments... Thanks for this link !
.
the code to get the real path is a bit different from one SDK to another so below we have three methods that deals with different SDKs.
getRealPathFromURI_API19(): returns real path for API 19 (or above but not tested)
getRealPathFromURI_API11to18(): returns real path for API 11 to API 18
getRealPathFromURI_below11(): returns real path for API below 11
public class RealPathUtil {
#SuppressLint("NewApi")
public static String getRealPathFromURI_API19(Context context, Uri uri){
String filePath = "";
String wholeID = DocumentsContract.getDocumentId(uri);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = { MediaStore.Images.Media.DATA };
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{ id }, null);
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
return filePath;
}
#SuppressLint("NewApi")
public static String getRealPathFromURI_API11to18(Context context, Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
String result = null;
CursorLoader cursorLoader = new CursorLoader(
context,
contentUri, proj, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
if(cursor != null){
int column_index =
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
result = cursor.getString(column_index);
}
return result;
}
public static String getRealPathFromURI_BelowAPI11(Context context, Uri contentUri){
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index
= cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
font: http://hmkcode.com/android-display-selected-image-and-its-real-path/
UPDATE 2016 March
To fix all problems with path of images i try create a custom gallery as facebook and other apps. This is because you can use just local files ( real files, not virtual or temporary) , i solve all problems with this library.
https://github.com/nohana/Laevatein (this library is to take photo from camera or choose from galery , if you choose from gallery he have a drawer with albums and just show local files)
Note This is an improvement in #user3516549 answer and I have check it on Moto G3 with Android 6.0.1
I have this issue so I have tried answer of #user3516549 but in some cases it was not working properly.
I have found that in Android 6.0(or above) when we start gallery image pick intent then a screen will open that shows recent images when user select image from this list we will get uri as
content://com.android.providers.media.documents/document/image%3A52530
while if user select gallery from sliding drawer instead of recent then we will get uri as
content://media/external/images/media/52530
So I have handle it in getRealPathFromURI_API19()
public static String getRealPathFromURI_API19(Context context, Uri uri) {
String filePath = "";
if (uri.getHost().contains("com.android.providers.media")) {
// Image pick from recent
String wholeID = DocumentsContract.getDocumentId(uri);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = {MediaStore.Images.Media.DATA};
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{id}, null);
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
return filePath;
} else {
// image pick from gallery
return getRealPathFromURI_BelowAPI11(context,uri)
}
}
EDIT1 : if you are trying to get image path of file in external sdcard in higher version then check my question
EDIT2 Here is complete code with handling virtual files and host other than com.android.providers I have tested this method with content://com.adobe.scan.android.documents/document/
EDIT:
Use this Solution here: https://stackoverflow.com/a/20559175/2033223
Works perfect!
First of, thank for your solution #luizfelipetx
I changed your solution a little bit. This works for me:
public static String getRealPathFromDocumentUri(Context context, Uri uri){
String filePath = "";
Pattern p = Pattern.compile("(\\d+)$");
Matcher m = p.matcher(uri.toString());
if (!m.find()) {
Log.e(ImageConverter.class.getSimpleName(), "ID for requested image not found: " + uri.toString());
return filePath;
}
String imgId = m.group();
String[] column = { MediaStore.Images.Media.DATA };
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{ imgId }, null);
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
return filePath;
}
Note: So we got documents and image, depending, if the image comes from 'recents', 'gallery' or what ever. So I extract the image ID first before looking it up.
One easy and best method copy file to the real path and then get their path I checked it 10 devices on android API-16 to API-30 working fine.
#Nullable
public static String createCopyAndReturnRealPath(
#NonNull Context context, #NonNull Uri uri) {
final ContentResolver contentResolver = context.getContentResolver();
if (contentResolver == null)
return null;
// Create file path inside app's data dir
String filePath = context.getApplicationInfo().dataDir + File.separator + "temp_file";
File file = new File(filePath);
try {
InputStream inputStream = contentResolver.openInputStream(uri);
if (inputStream == null)
return null;
OutputStream outputStream = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len;
while ((len = inputStream.read(buf)) > 0)
outputStream.write(buf, 0, len);
outputStream.close();
inputStream.close();
} catch (IOException ignore) {
return null;
}
return file.getAbsolutePath();
}
Hii here is my complete code for taking image from camera or galeery
//My variable declaration
protected static final int CAMERA_REQUEST = 0;
protected static final int GALLERY_REQUEST = 1;
Bitmap bitmap;
Uri uri;
Intent picIntent = null;
//Onclick
if (v.getId()==R.id.image_id){
startDilog();
}
//method body
private void startDilog() {
AlertDialog.Builder myAlertDilog = new AlertDialog.Builder(yourActivity.this);
myAlertDilog.setTitle("Upload picture option..");
myAlertDilog.setMessage("Where to upload picture????");
myAlertDilog.setPositiveButton("Gallery", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
picIntent = new Intent(Intent.ACTION_GET_CONTENT,null);
picIntent.setType("image/*");
picIntent.putExtra("return_data",true);
startActivityForResult(picIntent,GALLERY_REQUEST);
}
});
myAlertDilog.setNegativeButton("Camera", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
picIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(picIntent,CAMERA_REQUEST);
}
});
myAlertDilog.show();
}
//And rest of things
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==GALLERY_REQUEST){
if (resultCode==RESULT_OK){
if (data!=null) {
uri = data.getData();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
try {
BitmapFactory.decodeStream(getContentResolver().openInputStream(uri), null, options);
options.inSampleSize = calculateInSampleSize(options, 100, 100);
options.inJustDecodeBounds = false;
Bitmap image = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri), null, options);
imageofpic.setImageBitmap(image);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}else {
Toast.makeText(getApplicationContext(), "Cancelled",
Toast.LENGTH_SHORT).show();
}
}else if (resultCode == RESULT_CANCELED) {
Toast.makeText(getApplicationContext(), "Cancelled",
Toast.LENGTH_SHORT).show();
}
}else if (requestCode == CAMERA_REQUEST) {
if (resultCode == RESULT_OK) {
if (data.hasExtra("data")) {
bitmap = (Bitmap) data.getExtras().get("data");
uri = getImageUri(YourActivity.this,bitmap);
File finalFile = new File(getRealPathFromUri(uri));
imageofpic.setImageBitmap(bitmap);
} else if (data.getExtras() == null) {
Toast.makeText(getApplicationContext(),
"No extras to retrieve!", Toast.LENGTH_SHORT)
.show();
BitmapDrawable thumbnail = new BitmapDrawable(
getResources(), data.getData().getPath());
pet_pic.setImageDrawable(thumbnail);
}
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(getApplicationContext(), "Cancelled",
Toast.LENGTH_SHORT).show();
}
}
}
private String getRealPathFromUri(Uri tempUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = this.getContentResolver().query(tempUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
private Uri getImageUri(YourActivity youractivity, Bitmap bitmap) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
String path = MediaStore.Images.Media.insertImage(youractivity.getContentResolver(), bitmap, "Title", null);
return Uri.parse(path);
}
This helped me to get uri from Gallery and convert to a file for Multipart upload
File file = FileUtils.getFile(this, fileUri);
https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java
This code work for me in android 11 and 12
private static String getRealPathFromURI(Uri uri, Context context) {
Uri returnUri = uri;
Cursor returnCursor = context.getContentResolver().query(returnUri, null, null, null, null);
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
returnCursor.moveToFirst();
String name = (returnCursor.getString(nameIndex));
String size = (Long.toString(returnCursor.getLong(sizeIndex)));
File file = new File(context.getFilesDir(), name);
try {
InputStream inputStream = context.getContentResolver().openInputStream(uri);
FileOutputStream outputStream = new FileOutputStream(file);
int read = 0;
int maxBufferSize = 1 * 1024 * 1024;
int bytesAvailable = inputStream.available();
//int bufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
final byte[] buffers = new byte[bufferSize];
while ((read = inputStream.read(buffers)) != -1) {
outputStream.write(buffers, 0, read);
}
Log.e("File Size", "Size " + file.length());
inputStream.close();
outputStream.close();
Log.e("File Path", "Path " + file.getPath());
Log.e("File Size", "Size " + file.length());
} catch (Exception e) {
Log.e("Exception", e.getMessage());
}
return file.getPath();
}

Categories

Resources