I 'm working on an application to capture image from camera and get image from gallery the images will be shown on Image view every thing is work fine but my problem is in the image that in landscape orientation not appear in the right way can any one help me to convert the image in portrait orientation
this is my code
open.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, REQUEST_CODE);
}
});
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK)
try {
if (bitmap != null) {
bitmap.recycle();
}
InputStream stream = getContentResolver().openInputStream(
data.getData());
bitmap = BitmapFactory.decodeStream(stream);
stream.close();
pic.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
if (bitmap != null) {
bitmap.recycle();
}
bitmap = (Bitmap) data.getExtras().get("data");
pic.setImageBitmap(bitmap);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
Here are two helper methods that I use to rotate bitmaps to the correct orientation. You simply pass the method the bitmap you would like to rotate along with the absolute path to it's saved file location, which can be obtained with the getRealPathFromURI helper also supplied, and you will receive a correctly rotated bitmap.
Your code
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
if (bitmap != null) {
bitmap.recycle();
}
bitmap = (Bitmap) data.getExtras().get("data");
String absPath = getRealPathFromURI(data.getData());
Bitmap rotatedBitmap = rotateBitmap(absPath, bitmap);
pic.setImageBitmap(rotatedBitmap);
}
Helpers
/**
* Converts a Uri to an absolute file path
*
* #param contentUri Uri to be converted
* #return String absolute path of Uri
*/
public String getRealPathFromURI(Uri contentUri) {
// Can post image
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = this.getContentResolver().query(contentUri,
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);
}
/**
* Rotates the bitmap to the correct orientation for displaying
*
* #param filepath absolute path of original file
* #param originalBitmap original bitmap to be rotated
* #return
*/
private Bitmap rotateBitmap(String filepath, Bitmap originalBitmap) {
try {
// Find the orientation of the original file
ExifInterface exif = new ExifInterface(filepath);
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
Matrix matrix = new Matrix();
// Find correct rotation in degrees depending on the orientation of the original file
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
matrix.postRotate(90);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
matrix.postRotate(180);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
matrix.postRotate(270);
break;
default:
return originalBitmap;
}
// Create new rotated bitmap
Bitmap rotatedBitmap = Bitmap.createBitmap(originalBitmap, 0, 0, originalBitmap.getWidth(),
originalBitmap.getHeight(), matrix, true);
return rotatedBitmap;
} catch (IOException e) {
Log.d(TAG, "File cannot be found for rotating.");
return originalBitmap;
}
}
Related
I have been trying to save images to Firebase Storage but I noticed that almost all pictures saved from Gallery/Google Drive get rotated.(usually by 90 degrees)
Reading through older posts I realized that this is a common issue and I tried solving it by trying either solution from this post , or from this one , this one and I could go on.
After roughly 8 hours I finally decided to ask here. Is there a better and easier implementation to stop the images from getting rotated?
My last (and unsuccessful, obviously) implementation using ExifInterface (which returns all the time 0) is this one:
Selecting picture
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
OnActivityResult
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContext().getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
int rotateImageAngle = getPhotoOrientation(getContext(), selectedImage, filePath);
try {
bitmap = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), selectedImage);
// Log.d(TAG, String.valueOf(bitmap));
addPictureButton.setText("Done");
} catch (IOException e) {
e.printStackTrace();
}
if( bitmap != null)
{
RotateBitmap(bitmap , rotateImageAngle);
}
}
Helper methods
public int getPhotoOrientation(Context context, Uri imageUri, String imagePath){
int rotate = 0;
try {
context.getContentResolver().notifyChange(imageUri, null);
File imageFile = new File(imagePath);
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.i("RotateImage", "Exif orientation: " + orientation);
Log.i("RotateImage", "Rotate value: " + rotate);
} catch (Exception e) {
e.printStackTrace();
}
return rotate;
}
public static Bitmap RotateBitmap(Bitmap source, int angle)
{
Matrix matrix = new Matrix();
matrix.postRotate(angle);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
}
Note: If needed I will add the code that uploads images to Firebase
I have come to a solution thanks to this post.
I am going to post below a modified working version of the code for anybody that has this issue.
Fire up picture selection from gallery
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(intent, PICK_IMAGE_REQUEST);
OnActivityResult checking original roatation of the selected picture
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK && requestCode == PICK_IMAGE_REQUEST) {
// Get selected gallery image
Uri selectedPicture = data.getData();
// Get and resize profile image
String[] filePathColumn = {MediaStore.Images.Media.DATA};
// TRY getactvity() as well if not work
Cursor cursor = getContext().getContentResolver().query(selectedPicture, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
loadedBitmap = BitmapFactory.decodeFile(picturePath);
ExifInterface exif = null;
try {
File pictureFile = new File(picturePath);
exif = new ExifInterface(pictureFile.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
int orientation = ExifInterface.ORIENTATION_NORMAL;
if (exif != null)
orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
loadedBitmap = rotateBitmap(loadedBitmap, 90);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
loadedBitmap = rotateBitmap(loadedBitmap, 180);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
loadedBitmap = rotateBitmap(loadedBitmap, 270);
break;
}
imageView.setImageBitmap(loadedBitmap);
}
}
RotateBitmap method
public static Bitmap rotateBitmap(Bitmap bitmap, int degrees) {
Matrix matrix = new Matrix();
matrix.postRotate(degrees);
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
I have written a program which has a button which when clicked captures a photo through camera and want to set the captured image on the same activity below the button.
Everything works without giving an error. The image is also getting saved to the respective location. But the image is not getting displayed, which means something is going wrong.
Below is my Code for the above :
public class MainActivity extends ActionBarActivity {
Button b1;
private File imageFile;
ImageView img;
private Uri uri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.buttonPicture);
img = (ImageView) findViewById(R.id.imageView1);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
imageFile = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"test.jpeg");
uri = Uri.fromFile(imageFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, 0);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (requestCode == 0 && data != null) {
switch (resultCode) {
case Activity.RESULT_OK:
if (imageFile.exists()) {
Bitmap photo = (Bitmap) data.getExtras().get(
MediaStore.EXTRA_OUTPUT);
previewCapturedImage();
img.setImageBitmap(photo);
} else {
Toast.makeText(getBaseContext(), "File was not saved",
Toast.LENGTH_SHORT).show();
}
break;
case Activity.RESULT_CANCELED:
break;
default:
break;
}
}
}
private void previewCapturedImage() {
try {
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(uri.getPath(),
options);
img.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
Once you press Ok button after capturing image, you can take the captured image from the Extras using Intent(data in your case) parameter received through onActivityResult
Simply use this code inside onActivityResult
Bitmap photo = (Bitmap) data.getExtras().get("data");
imgViewLogo.setImageBitmap(photo);
Try with below code:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (requestCode == 0 && data != null) {
switch (resultCode) {
case Activity.RESULT_OK:
if (imageFile.exists()) {
private String selectedImagePath;
Uri selectedImageUri = data.getData();
String filePath = null;
String filemanagerstring = selectedImageUri.getPath();
selectedImagePath = getPath(selectedImageUri);
if (selectedImagePath != null) {
filePath = selectedImagePath;
} else if (filemanagerstring != null) {
filePath = filemanagerstring;
} else {
Toast.makeText(getApplicationContext(), R.string.unknownPath, Toast.LENGTH_LONG).show();
if (filePath != null) {
decodeFile(filePath);
} else {
bitmap = null;
}
} else {
Toast.makeText(getBaseContext(), "File was not saved",
Toast.LENGTH_SHORT).show();
}
break;
case Activity.RESULT_CANCELED:
break;
default:
break;
}
}
}
//getPath method
public String getPath(Uri uri) {
String[] projection = { MediaColumns.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
//decodeFile method
public void decodeFile(String filePath) {
private Bitmap bitmap;
try {
File f = new File(filePath);
ExifInterface exif = new ExifInterface(f.getPath());
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int angle = 0;
if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
angle = 90;
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
angle = 180;
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
angle = 270;
}
Matrix mat = new Matrix();
mat.postRotate(angle);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
Bitmap bmp = BitmapFactory.decodeStream(new FileInputStream(f), null, options);
bitmap = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), mat, true);
ByteArrayOutputStream outstudentstreamOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outstudentstreamOutputStream);
img.setImageBitmap(selfieBitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
Hi am capturing an image through camera intent it works good but my problem is that am not getting preview of that image
my requirement is very simple, after clicking of photo through camera it must ask me to SAVE or DISCARD this image if i press SAVE then it get save into sd card thats it...
here is my code
private void openCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
capturedFile = new File(Environment.getExternalStorageDirectory(),
"tmp_nookster_profilepic"
+ String.valueOf(System.currentTimeMillis()) + ".jpg");
mImageCaptureUri = Uri.fromFile(capturedFile);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
mImageCaptureUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, PICK_FROM_CAMERA_NO_CROP);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK)
return;
switch (requestCode) {
case PICK_FROM_CAMERA_NO_CROP: {
iu.SaveCapturedImage(BitmapFactory.decodeFile(capturedFile
.getAbsolutePath()));
try {
if (capturedFile.exists())
capturedFile.delete();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
break;
here "iu" is object of ImageUtility class and "SaveCapturedImage" is method to store that captured image in SdCard
You can get a preview of the captured File as this:
Bitmap getPreview(File image) {
final int THUMBNAIL_SIZE = 72;
BitmapFactory.Options bounds = new BitmapFactory.Options();
bounds.inJustDecodeBounds = true;
BitmapFactory.decodeFile(image.getPath(), bounds);
if ((bounds.outWidth == -1) || (bounds.outHeight == -1))
return null;
int originalSize = (bounds.outHeight > bounds.outWidth) ? bounds.outHeight
: bounds.outWidth;
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = originalSize / THUMBNAIL_SIZE;
return BitmapFactory.decodeFile(image.getPath(), opts);
}
then you can show the Bitmap in an ImageView and present the user with Save/Delete buttons.
You have to remove line from your code.
if (resultCode != RESULT_OK)
return;
Use following code :
if (resultCode == RESULT_OK)
{
try
{
Bitmap bitmap=null;
String imageId = convertImageUriToFile(imageUri,AddRecipes.this);
bitmap = BitmapFactory.decodeFile(imageId);
}}
public static String convertImageUriToFile (Uri contentUri, Activity activity)
{
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader cursorLoader = new CursorLoader(activity.getApplicationContext(),contentUri, proj, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
In my app i am using this code to get Image from Gallery and Camera:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 10 && resultCode == Activity.RESULT_OK) {
Uri contentUri = data.getData();
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
imagePath = cursor.getString(column_index);
//Bitmap croppedImage = BitmapFactory.decodeFile(imagePath);
tempBitmap = BitmapFactory.decodeFile(imagePath);
if(!(tempBitmap == null))
{
// here i am changing display to the tempBitmap
photoBitmap = Bitmap.createScaledBitmap(tempBitmap, display.getWidth(), display.getHeight(), true);
//photoBitmap = Bitmap.createBitmap(tempBitmap, 0, 0, tempBitmap.getWidth(), tempBitmap.getHeight());
takePhotoFromGallery = true;// edited
}
else
Toast.makeText(getApplicationContext(), "Image is not valid", Toast.LENGTH_SHORT).show();
}
if(resultCode == RESULT_OK && requestCode==TAKE_PHOTO_CODE){
final File file = getTempFile(this);
try {
tempBitmap = Media.getBitmap(getContentResolver(), Uri.fromFile(file));
photoBitmap = Bitmap.createScaledBitmap(tempBitmap, display.getWidth(), display.getHeight(), true);
takePhotoFromCamera = true;
// do whatever you want with the bitmap (Resize, Rename, Add To Gallery, etc)
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Now, all works fine. But i got Image as Stratch.
I thaught it is because this line:
photoBitmap = Bitmap.createScaledBitmap(tempBitmap, display.getWidth(), display.getHeight(), true);
here i am stratching the image width,height with display's width,height.
I want is the Image should be Dispaly as we can normaly show thew image in gallery. So how to make it possible ???
This is the image which i am snaping from the Camera:
And Now this is What i see in my Application:
Now Second image got little stratch. as because of that line code.
So what should i have to do to make is normal in its height and width ??
Thanks.
Thanks.
Use ImageView and set scale type of image view to Center-Inside.
This question already has answers here:
Why does an image captured using camera intent gets rotated on some devices on Android?
(23 answers)
Closed 4 years ago.
I'm working at an application in android which uses camera to take photos.For starting the camera I'm using an intent ACTION_IMAGE_CAPTURE like this:
Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File image=new File(Environment.getExternalStorageDirectory(),"PhotoContest.jpg");
camera.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(image));
imageUri=Uri.fromFile(image);
startActivityForResult(camera,1);
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode){
case 1:
if (resultCode == Activity.RESULT_OK) {
selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
image= (ImageView) findViewById(R.id.imageview);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media
.getBitmap(cr, selectedImage);
image.setImageBitmap(bitmap);
Toast.makeText(this, selectedImage.toString(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
.show();
Log.e("Camera", e.toString());
}
}
else
if(resultCode == Activity.RESULT_CANCELED) {
Toast.makeText(EditPhoto.this, "Picture could not be taken.", Toast.LENGTH_SHORT).show();
}
}
}
The problem is that all the photos that are taken are rotated with 90 degrees-horizontally aligned.
I've also put this into my manifest file:
<activity android:name=".EditPhoto">
android:screenOrientation="portrait"
</activity>
But still with no result!So can anyone help me???
http://developer.android.com/reference/android/media/ExifInterface.html
http://developer.android.com/reference/android/media/ExifInterface.html#TAG_ORIENTATION
So if in
Activity.onActivityResult(data, request, result) {
if (request == PHOTO_REQUEST && result == RESULT_OK) {
...
Uri imageUri = ...
File imageFile = new File(imageUri.toString());
ExifInterface exif = new ExifInterface(imageFile.getAbsolutePath());
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;
}
Canvas canvas = new Canvas(bitmap);
canvas.rotate(rotate);
}
Does this help at all?
Just to add to Greg's great answer, here's a whole "category" to do the job:
public static int neededRotation(File ff)
{
try
{
ExifInterface exif = new ExifInterface(ff.getAbsolutePath());
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
if (orientation == ExifInterface.ORIENTATION_ROTATE_270)
{ return 270; }
if (orientation == ExifInterface.ORIENTATION_ROTATE_180)
{ return 180; }
if (orientation == ExifInterface.ORIENTATION_ROTATE_90)
{ return 90; }
return 0;
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
return 0;
}
you'd use it more or less like this ...
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == REQUEST_IMAGE_CAPTURE) // && resultCode == RESULT_OK )
{
try
{
Bitmap cameraBmp = MediaStore.Images.Media.getBitmap(
State.mainActivity.getContentResolver(),
Uri.fromFile( Utils.tempFileForAnImage() ) );
cameraBmp = ThumbnailUtils.extractThumbnail(cameraBmp, 320,320);
// NOTE incredibly useful trick for cropping/resizing square
// http://stackoverflow.com/a/17733530/294884
Matrix m = new Matrix();
m.postRotate( Utils.neededRotation(Utils.tempFileForAnImage()) );
cameraBmp = Bitmap.createBitmap(cameraBmp,
0, 0, cameraBmp.getWidth(), cameraBmp.getHeight(),
m, true);
yourImageView.setImageBitmap(cameraBmp);
// to convert to bytes...
ByteArrayOutputStream baos = new ByteArrayOutputStream();
cameraBmp.compress(Bitmap.CompressFormat.JPEG, 75, baos);
//or say cameraBmp.compress(Bitmap.CompressFormat.PNG, 0, baos);
imageBytesRESULT = baos.toByteArray();
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
return;
}
}
Hope it saves someone some typing in the future.
The above answer is very thorough, but I found I had to do a little bit more in order for every case to work, especially if you're dealing with images from other sources such as the Gallery or Google Photos. Here's my DetermineOrientation method. I have a utility class where this is located so I have to pass in the Activity in order to use managedQuery(which btw is deprecated so use cautiously). The reason I have to use two methods is because, depending on the source of the image, ExifInterface will not work. For instance, if I take a camera photo, Exif works fine. However, if I'm also choosing images from the Gallery or Google Drive, Exif does not work and always returns 0. Hope this helps someone.
public static int DetermineOrientation(Activity activity, Uri fileUri)
{
int orientation = -1;
int rotate = 0;
try {
ExifInterface exif = new ExifInterface(fileUri.getPath());
orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
rotate = 0;
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(rotate == 0)
{
String[] orientationColumn = {MediaStore.Images.Media.ORIENTATION};
Cursor cur = activity.managedQuery(fileUri, orientationColumn, null, null, null);
orientation = -1;
if (cur != null && cur.moveToFirst()) {
orientation = cur.getInt(cur.getColumnIndex(orientationColumn[0]));
}
if(orientation != -1)
{
rotate = orientation;
}
}
return rotate;
}