This question already has answers here:
Why does an image captured using camera intent gets rotated on some devices on Android?
(23 answers)
Closed 6 years ago.
in my app I need to load image from camera.
This is the code I've used:
private void openCamera()
{
mMediaUri =getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
Intent photoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
photoIntent.putExtra(MediaStore.EXTRA_OUTPUT, mMediaUri);
startActivityForResult(photoIntent, REQUEST_TAKE_PHOTO);
}
private Uri getOutputMediaFileUri(int mediaTypeImage)
{
//check for external storage
if(isExternalStorageAvaiable())
{
File mediaStorageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
String fileName = "";
String fileType = "";
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new java.util.Date());
fileName = "IMG_"+timeStamp;
fileType = ".jpg";
File mediaFile;
try
{
mediaFile = File.createTempFile(fileName,fileType,mediaStorageDir);
Log.i("st","File: "+Uri.fromFile(mediaFile));
}
catch (IOException e)
{
e.printStackTrace();
Log.i("St","Error creating file: " + mediaStorageDir.getAbsolutePath() +fileName +fileType);
return null;
}
return FileProvider.getUriForFile(getActivity(),BuildConfig.APPLICATION_ID + ".provider", mediaFile);
}
//something went wrong
return null;
}
private boolean isExternalStorageAvaiable()
{
String state = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(state))
{
return true;
}
else
{
return false;
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == DIALOG_CODE)
{
String s = data.getStringExtra("choose");
if(s.equals(getString(R.string.takephoto)))
{
openCamera();
}
else if(s.equals(getString(R.string.library)))
{
openGallery();
}
}
else if(resultCode == RESULT_OK)
{
if (requestCode == REQUEST_TAKE_PHOTO || requestCode == REQUEST_PICK_PHOTO) //dalla fotocamera
{
if (data != null) //caso galleria
{
mMediaUri = data.getData();
}
Picasso.with(getActivity()).load(mMediaUri).resize(1280, 1280).transform(new RoundedTransformation()).centerCrop().into(photo, new Callback()
{
public void onSuccess()
{
}
#Override
public void onError() {
}
});
}
}
}
and it works but it gives me this error: if I take a photo like this:
it loads a picture in imageview in this way:
but if I load the picture from the gallery, it works ok.
What's the error here?
Thanks
You have to rotate image using ExifInterface.
Image rotate based on image capture angle.
ExifInterface will rotate image even if you click photo from any angle.
It will display properly.
File mediaFile = new File(mediaPath);
Bitmap bitmap;
if (mediaFile.exists()) {
if (isImage(mediaPath)) {
Bitmap myBitmap = BitmapFactory.decodeFile(mediaFile.getAbsolutePath());
int height = (myBitmap.getHeight() * 512 / myBitmap.getWidth());
Bitmap scale = Bitmap.createScaledBitmap(myBitmap, 512, height, true);
int rotate = 0;
try {
exif = new ExifInterface(mediaFile.getAbsolutePath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED);
switch (orientation) {
case ExifInterface.ORIENTATION_NORMAL:
rotate = 0;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
}
Matrix matrix = new Matrix();
matrix.postRotate(rotate);
Bitmap rotateBitmap = Bitmap.createBitmap(scale, 0, 0, scale.getWidth(),
scale.getHeight(), matrix, true);
displayImage.setImageBitmap(rotateBitmap);
}
}
public static boolean isImage(String str) {
boolean temp = false;
String[] arr = { ".jpeg", ".jpg", ".png", ".bmp", ".gif" };
for (int i = 0; i < arr.length; i++) {
temp = str.endsWith(arr[i]);
if (temp) {
break;
}
}
return temp;
}
Related
I take photo bt camera on mode landscape, after upload to server...It was landscape to.
But when i load to imageview then display vertical like below image:
I using Picasso to load image to Imageview.I want display like original image on ImageView...
Please suggest for me...tks so much!
public static void makeImageRequest(Context context, ImageView imageView, final String imageUrl, ProgressBar progressBar) {
final int defaultImageResId = R.drawable.ic_member;
Picasso.with(context)
.load(imageUrl)
.error(defaultImageResId)
.resize(80, 80)
.into(imageView);
}
ImageView:
<ImageView
android:layout_centerInParent="true"
android:padding="#dimen/_8sdp"
android:id="#+id/img_photo"
android:layout_width="#dimen/_80sdp"
android:layout_height="#dimen/_80sdp"
android:layout_gravity="center"
android:scaleType="fitCenter"
android:adjustViewBounds="true" />
URL:
https://arubaitobsv.s3-ap-northeast-1.amazonaws.com/images/1487816629838-20170223_092312_HDR.jpg
The problem issued here
Picasso auto rotates by 90 degrees an image coming from the web that has the following EXIF data:
Resolution : 3264 x 2448
Orientation : rotate 90
try this code with picasso:
Picasso.with(MainActivity.this)
.load(imageURL) // web image url
.fit().centerInside()
.transform(transformation)
.rotate(90) //if you want to rotate by 90 degrees
.error(R.drawable.ic_launcher)
.placeholder(R.drawable.ic_launcher)
.into(imageview)
});
You can also use Glide:
dependencies {
// Your app's other dependencies
compile 'com.github.bumptech.glide:glide.3.7.0'
}
laod image using:
Glide.with(this).load("image_url").into(imageView);
public class ImageRotationDetectionHelper {
public static int getCameraPhotoOrientation(String imageFilePath) {
int rotate = 0;
try {
ExifInterface exif;
exif = new ExifInterface(imageFilePath);
String exifOrientation = exif
.getAttribute(ExifInterface.TAG_ORIENTATION);
Log.d("exifOrientation", exifOrientation);
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
Log.d(ImageRotationDetectionHelper.class.getSimpleName(), "orientation :" + orientation);
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;
}
} catch (IOException e) {
e.printStackTrace();
}
return rotate;
}
}
Try this way it will work
public class MainActivity extends Activity {
private ImageView imgFromCameraOrGallery;
private Button btnCamera;
private Button btnGallery;
private String imgPath;
final private int PICK_IMAGE = 1;
final private int CAPTURE_IMAGE = 2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgFromCameraOrGallery = (ImageView) findViewById(R.id.imgFromCameraOrGallery);
btnCamera = (Button) findViewById(R.id.btnCamera);
btnGallery = (Button) findViewById(R.id.btnGallery);
btnCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());
startActivityForResult(intent, CAPTURE_IMAGE);
}
});
btnGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, ""), PICK_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == CAPTURE_IMAGE) {
setCapturedImage(getImagePath());
} else if (requestCode == PICK_IMAGE) {
imgFromCameraOrGallery.setImageBitmap(BitmapFactory.decodeFile(getAbsolutePath(data.getData())));
}
}
}
private String getRightAngleImage(String photoPath) {
try {
ExifInterface ei = new ExifInterface(photoPath);
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int degree = 0;
switch (orientation) {
case ExifInterface.ORIENTATION_NORMAL:
degree = 0;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
degree = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
degree = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
degree = 270;
break;
case ExifInterface.ORIENTATION_UNDEFINED:
degree = 0;
break;
default:
degree = 90;
}
return rotateImage(degree,photoPath);
} catch (Exception e) {
e.printStackTrace();
}
return photoPath;
}
private String rotateImage(int degree, String imagePath){
if(degree<=0){
return imagePath;
}
try{
Bitmap b= BitmapFactory.decodeFile(imagePath);
Matrix matrix = new Matrix();
if(b.getWidth()>b.getHeight()){
matrix.setRotate(degree);
b = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(),
matrix, true);
}
FileOutputStream fOut = new FileOutputStream(imagePath);
String imageName = imagePath.substring(imagePath.lastIndexOf("/") + 1);
String imageType = imageName.substring(imageName.lastIndexOf(".") + 1);
FileOutputStream out = new FileOutputStream(imagePath);
if (imageType.equalsIgnoreCase("png")) {
b.compress(Bitmap.CompressFormat.PNG, 100, out);
}else if (imageType.equalsIgnoreCase("jpeg")|| imageType.equalsIgnoreCase("jpg")) {
b.compress(Bitmap.CompressFormat.JPEG, 100, out);
}
fOut.flush();
fOut.close();
b.recycle();
}catch (Exception e){
e.printStackTrace();
}
return imagePath;
}
private void setCapturedImage(final String imagePath){
new AsyncTask<Void,Void,String>(){
#Override
protected String doInBackground(Void... params) {
try {
return getRightAngleImage(imagePath);
}catch (Throwable e){
e.printStackTrace();
}
return imagePath;
}
#Override
protected void onPostExecute(String imagePath) {
super.onPostExecute(imagePath);
imgFromCameraOrGallery.setImageBitmap(decodeFile(imagePath));
}
}.execute();
}
public Bitmap decodeFile(String path) {
try {
// Decode deal_image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_SIZE && o.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeFile(path, o2);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
public String getAbsolutePath(Uri uri) {
if(Build.VERSION.SDK_INT >= 19){
String id = "";
if(uri.getLastPathSegment().split(":").length > 1)
id = uri.getLastPathSegment().split(":")[1];
else if(uri.getLastPathSegment().split(":").length > 0)
id = uri.getLastPathSegment().split(":")[0];
if(id.length() > 0){
final String[] imageColumns = {MediaStore.Images.Media.DATA };
final String imageOrderBy = null;
Uri tempUri = getUri();
Cursor imageCursor = getContentResolver().query(tempUri, imageColumns, MediaStore.Images.Media._ID + "=" + id, null, imageOrderBy);
if (imageCursor.moveToFirst()) {
return imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
}else{
return null;
}
}else{
return null;
}
}else{
String[] projection = { MediaStore.MediaColumns.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
}
private Uri getUri() {
String state = Environment.getExternalStorageState();
if(!state.equalsIgnoreCase(Environment.MEDIA_MOUNTED))
return MediaStore.Images.Media.INTERNAL_CONTENT_URI;
return MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
}
public Uri setImageUri() {
Uri imgUri;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/",getString(R.string.app_name) + Calendar.getInstance().getTimeInMillis() + ".png");
imgUri = Uri.fromFile(file);
imgPath = file.getAbsolutePath();
}else {
File file = new File(getFilesDir() ,getString(R.string.app_name) + Calendar.getInstance().getTimeInMillis()+ ".png");
imgUri = Uri.fromFile(file);
this.imgPath = file.getAbsolutePath();
}
return imgUri;
}
public String getImagePath() {
return imgPath;
}
}
This code is all you need to check and fix the rotation, then once you have the filePath then parse the path string as a Uri in the Picasso Load
Loading into Picasso:
String imagePath = /* your image path here */
Picasso.get()
.load(Uri.parseString(getRightAngleImage(imagePath)))
.into(/* your ImageView id here */);
Function for rotating and retrieving filePath:
private String getRightAngleImage(String photoPath) {
try {
ExifInterface ei = new ExifInterface(photoPath);
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int degree = 0;
switch (orientation) {
case ExifInterface.ORIENTATION_NORMAL:
degree = 0;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
degree = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
degree = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
degree = 270;
break;
case ExifInterface.ORIENTATION_UNDEFINED:
degree = 0;
break;
default:
degree = 90;
}
return rotateImage(degree,photoPath);
} catch (Exception e) {
e.printStackTrace();
}
return photoPath;
}
private String rotateImage(int degree, String imagePath){
if(degree<=0){
return imagePath;
}
try{
Bitmap b= BitmapFactory.decodeFile(imagePath);
Matrix matrix = new Matrix();
if(b.getWidth()>b.getHeight()){
matrix.setRotate(degree);
b = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(),
matrix, true);
}
FileOutputStream fOut = new FileOutputStream(imagePath);
String imageName = imagePath.substring(imagePath.lastIndexOf("/") + 1);
String imageType = imageName.substring(imageName.lastIndexOf(".") + 1);
FileOutputStream out = new FileOutputStream(imagePath);
if (imageType.equalsIgnoreCase("png")) {
b.compress(Bitmap.CompressFormat.PNG, 100, out);
}else if (imageType.equalsIgnoreCase("jpeg")|| imageType.equalsIgnoreCase("jpg")) {
b.compress(Bitmap.CompressFormat.JPEG, 100, out);
}
fOut.flush();
fOut.close();
b.recycle();
}catch (Exception e){
e.printStackTrace();
}
return imagePath;
}
Thanks to Aditya Vyas-Lahkan for the function, it worked for me with some minor modifications.
Hope this helps!
I'm duplicating answer by Prakhar1001! Try use this library Compressor.
This solved Picasso rotation issue. Just compress your image file before uploading it to the server.
This is the correct implementation.
First know what's the correct angle:
fun getRotation(context: Context, selectedImage: Uri): Float {
val ei = ExifInterface(context.contentResolver.openInputStream(selectedImage)!!)
val orientation: Int =
ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL)
return when (orientation) {
ExifInterface.ORIENTATION_NORMAL -> 0f
ExifInterface.ORIENTATION_ROTATE_90 -> 90f
ExifInterface.ORIENTATION_ROTATE_180 -> 180f
ExifInterface.ORIENTATION_ROTATE_270 -> 270f
ExifInterface.ORIENTATION_UNDEFINED -> 0f
else -> 90f
}
}
Then,
val inputStream = context.contentResolver.openInputStream(IMAGE_URI_HERE)
val file = File(filesDir, "image.YOUR_EXT")
if (inputStream != null) {
val outputStream: OutputStream = FileOutputStream(file)
val BUFFER_SIZE = 1024 * 2
val buffer = ByteArray(BUFFER_SIZE)
var n: Int
try {
BufferedInputStream(inputStream, BUFFER_SIZE).use { `in` ->
BufferedOutputStream(outputStream, BUFFER_SIZE).use { out ->
while (`in`.read(buffer, 0, BUFFER_SIZE).also { n = it } != -1) {
out.write(buffer, 0, n)
}
out.flush()
}
}
} catch (e: IOException) {
e.printStackTrace()
myFile.isSuccess = false
myFile.errorMsg = "05" //IOException 2
return myFile
}
inputStream.close()
outputStream.close()
}
Then create bitmap from the file and rotate
val bitmapOriginal = BitmapFactory.decodeFile(file.filePath)
val rotatedBitmap = rotateBitmap(bitmapOriginal, getRotation(context, uri)) //This is your final Bitmap
fun rotateImage(img: Bitmap, degree: Float): Bitmap {
val matrix = Matrix()
matrix.postRotate(degree)
val rotatedImg = Bitmap.createBitmap(img, 0, 0, img.width, img.height, matrix, true)
img.recycle()
return rotatedImg
}
At last, delete the file after work is done
file.delete()
I'm trying to load an image from gallery in a ImageView. This code work correctly on Huawei p10, but don't work correctly on Samsung s5 and other devices. When i load the image the orientation is not correctly.
I'm using this function to load from gallery but the orientation is always 0.
public void loadPostImage(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE1);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE1) {
selectedImageUri = data.getData();
if (null != selectedImageUri) {
flag=true;
path = selectedImageUri.getPath();
int orientation = getOrientation(getApplicationContext(), selectedImageUri);
Log.e("image path", path + "");
image_post.setImageURI(selectedImageUri);
}
}
}
}
private static int getOrientation(Context context, Uri photoUri) {
Cursor cursor = context.getContentResolver().query(photoUri,
new String[]{MediaStore.Images.ImageColumns.ORIENTATION}, null, null, null);
if (cursor.getCount() != 1) {
cursor.close();
return -1;
}
cursor.moveToFirst();
int orientation = cursor.getInt(0);
cursor.close();
cursor = null;
return orientation;
}
I tried also with EXIF. But nothing is changed.
public void controlRotate(Uri photoUri) throws IOException {
ExifInterface exif = new ExifInterface(photoUri.getPath());
int exifRotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED);
switch (exifRotation) {
case ExifInterface.ORIENTATION_ROTATE_90: {
float photoRotation = 90.0f;
break;
}
case ExifInterface.ORIENTATION_ROTATE_180: {
float photoRotation = 180.0f;
break;
}
case ExifInterface.ORIENTATION_ROTATE_270: {
float photoRotation = 270.0f;
break;
}
}
}
I resolved the problem using this snippet
public void orientation(Uri selectedImageUri){
Uri uri = selectedImageUri; // the URI you've received from the other app
InputStream in = null;
try {
in = getContentResolver().openInputStream(uri);
ExifInterface exifInterface = new ExifInterface(in);
int rotation = 0;
int orientation = exifInterface.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
rotation = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotation = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotation = 270;
break;
}
// Now you can extract any Exif tag you want
// Assuming the image is a JPEG or supported raw format
} catch (IOException e) {
// Handle any errors
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ignored) {}
}
}
}
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();
}
}
I have been stuck in camera for 6 days but not getting any proper solution. When I am capturing image through camera intent, image is being rotated. I tried to fix the orientation but sometimes it's not giving bitmap value in onActivityResult(). It shows a black screen when I try to set image in ImageView. Here is my code Please help me -
//call intent to capture image
captureBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
try {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null)
{
startActivityForResult(takePictureIntent,AlletConstants.CAPTURE_RECEIPT_IMAGE);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case AlletConstants.CAPTURE_RECEIPT_IMAGE:
if(data != null)
{
Uri qrcodeImageUri = data.getData();
bitmapReceiptImage = handleQrBarCodeImage(qrcodeImageUri);
mImageCaptureUri = AlletCommonUtility.bitmapToUri(getActivity(), bitmapReceiptImage);
doCrop();
AlletCommonUtility.showToast(getActivity(),"Uri = "+mImageCaptureUri);
}
break;
case AlletConstants.CROP_RECEIPT_FROM_CAMERA:
if(data != null)
{
Bundle qrcodeextras = data.getExtras();
if (qrcodeextras != null) {
Bitmap cropBitmap = qrcodeextras.getParcelable("data");
receiptImageView.setImageBitmap(cropBitmap);
bitmapReceiptImage = cropBitmap;
}
File qrcodeFile = new File(mImageCaptureUri.getPath());
if (qrcodeFile.exists())
qrcodeFile.delete();
}
break;
default:
break;
}
}
// use to get bitmap from uri
private Bitmap handleReceiptImage(Uri selectedImageUri)
{
String[] filePathColumn = {MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(selectedImageUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
Bitmap bitmap = setCameraImageRotation(picturePath);
return bitmap;
}
private Bitmap setCameraImageRotation(String picturePath)
{
Bitmap bitmapQrBarImage = null;
try {
File f = new File(picturePath);
ExifInterface exif = new ExifInterface(f.getPath());
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
AlletCommonUtility.showToast(getActivity(), "Orienattion = "+orientation);
Matrix mat = new Matrix();
mat.postRotate(getImageOrientation(orientation));
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize= 4;
Bitmap bmp = BitmapFactory.decodeStream(new FileInputStream(f), null, options);
bitmapQrBarImage = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), mat, true);
if (bitmapQrBarImage != null) {
AlletCommonUtility.showToast(getActivity(), "CAMERA_PIC_SELECTION = "+bitmapQrBarImage);
}
}
catch (IOException e) {
Log.w("TAG", "-- Error in setting image");
}
catch(OutOfMemoryError oom) {
Log.w("TAG", "-- OOM Error in setting image");
}
return bitmapQrBarImage;
}
// Use to crop image
private void doCrop() {
final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/*");
List<ResolveInfo> list = getActivity().getPackageManager().queryIntentActivities( intent, 0 );
int size = list.size();
if (size == 0) {
AlletCommonUtility.showToast(getActivity(), AlletMessage.NOT_CROP_IMAGE);
return;
} else {
intent.setData(mImageCaptureUri);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 200);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
if (size == 1) {
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
startActivityForResult(i, AlletConstants.CROP_RECEIPT_FROM_CAMERA);
} else {
for (ResolveInfo res : list) {
final CropOption co = new CropOption();
co.title = getActivity().getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
co.icon = getActivity().getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);
co.appIntent= new Intent(intent);
co.appIntent.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
cropOptions.add(co);
}
CropOptionAdapter adapter = new CropOptionAdapter(getActivity(), cropOptions);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Choose Crop App");
builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dialog, int item ) {
startActivityForResult( cropOptions.get(item).appIntent, AlletConstants.CROP_RECEIPT_FROM_CAMERA);
}
});
builder.setOnCancelListener( new DialogInterface.OnCancelListener() {
#Override
public void onCancel( DialogInterface dialog ) {
if (mImageCaptureUri != null ) {
getActivity().getContentResolver().delete(mImageCaptureUri, null, null );
mImageCaptureUri = null;
}
}
} );
AlertDialog alert = builder.create();
alert.show();
}
}
}
// use to rotate captured image from device camera
public static int getImageOrientation(int rotation)
{
int angle = 0;
switch (rotation) {
case 0:
angle = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
angle = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
angle = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
angle = 270;
break;
default:
break;
}
return angle;
}
I am getting image in landscape mode but not in potrait mode. Camera preview automatically rotates by 90 degrees after capturing image.
It is because of the image's EXIF data. You need to use a rotation method.
Depending on your build-in Camera orientation and orientation of device the pictures will have different rotations. You check the rotation of your particular image through ExifInterface.
/**
* #param filename Path to image file
* #param captureTime Time when image file was created
*/
public static int extractExifOrientationTagFromImageFile(String filename, long creationTime) {
/* The issue is on some devices, there's a bug that makes the picture taken saved in your app folder without proper
exif tags while a properly rotated image is saved in the android default folder (even though it shouldn't be).
Now what we do is recording the time when we're starting the camera app. Then we query
the Media Provider to see if any pictures were saved after this timestamp we've saved. That means most likely Android OS
saved the properly rotated picture in the default folder and of course put an entry in the media store and we can use the
rotation information from this row. */
int imageRotation = -1;
long imageFileSize = new File(filename).length();
Cursor mediaFileCursor = getContext().getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Images.ImageColumns.ORIENTATION, MediaStore.MediaColumns.SIZE },
MediaStore.MediaColumns.DATE_ADDED + " >= ?", new String[] { String.valueOf(creationTime / 1000 - 1) },
MediaStore.MediaColumns.DATE_ADDED + " DESC");
if((mediaFileCursor != null) && (mediaFileCursor.getCount() != 0)) {
while(mediaFileCursor.moveToNext()) {
long mediaFileSize = getLongFromCursor(mediaFileCursor, MediaStore.MediaColumns.SIZE);
// Extra check to make sure that we are getting the orientation from the proper file
if(mediaFileSize == imageFileSize) {
imageRotation = getIntFromCursor(mediaFileCursor, MediaStore.Images.ImageColumns.ORIENTATION);
break;
}
}
}
/* Now if the rotation at this point is still -1, then that means this is one of the devices with proper rotation information. */
if(imageRotation == -1) {
ExifInterface exif = null;
try {
exif = new ExifInterface(filename);
}
catch (IOException e) {
e.printStackTrace();
}
imageRotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, -1);
}
return imageRotation;
}
private static final int COLUMN_NOT_EXISTS = -1;
public static Long getLongFromCursor(Cursor cursor, String columnName) {
int columnIndex;
if((columnIndex = cursor.getColumnIndex(columnName)) != COLUMN_NOT_EXISTS) {
return cursor.getLong(columnIndex);
}
else {
return null;
}
}
public static Integer getIntFromCursor(Cursor cursor, String columnName) {
int columnIndex;
if((columnIndex = cursor.getColumnIndex(columnName)) != COLUMN_NOT_EXISTS) {
return cursor.getInt(columnIndex);
}
else {
return null;
}
}
Now when you have your image rotation you can rotate it's bitmap properly:
int imageRotation = extractExifOrientationTagFromImageFile(lastCapturedMediaUriPath, cameraAppInvokeTime);
Matrix matrix = new Matrix();
switch(imageRotation) {
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:
break;
}
final Bitmap loadedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
This question already has answers here:
Photo rotate 90 degree while capture in some phones
(3 answers)
Taking picture with camera intent rotate picture in portrait mode android
(5 answers)
Closed 9 years ago.
in my Android app I capture the photo in portrait mode but when photo is saved is convert in landscape mode but I want to save photo in portrait mode
CaptureActivity.java
public class CaptureActivity extends Activity
{
// Activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;
// imageview for display captured image
ImageView imagecapture;
// file url to store image/video
public Uri fileUri;
// Classes For Database
private SQLiteDatabase mSQLiteDatabase = null;
private DB_Helper mDB_Helper = null;
public static ContextWrapper contextWrapper;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.capturephoto);
imagecapture=(ImageView)findViewById(R.id.imagecapture);
contextWrapper = new ContextWrapper(getApplicationContext());
// Checking camera availability
if(!isDeviceSupportCamera())
{
Toast.makeText(getApplicationContext(),"Sorry! Your device doesn't support camera", Toast.LENGTH_LONG).show();
// will close the app if the device does't have camera
finish();
}
else
{
captureImage();
}
}
/* Opening DB */
private void Open_Database()
{
mDB_Helper = new DB_Helper(this);
mSQLiteDatabase = mDB_Helper.getWritableDatabase();
}
/* Closing DB */
private void Close_Database()
{
if (mSQLiteDatabase != null && mDB_Helper != null) {
mSQLiteDatabase.close();
mDB_Helper.close();
}
}
/**
* Checking device has camera hardware or not
* */
private boolean isDeviceSupportCamera()
{
if(getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA))
{
// this device has a camera
return true;
}
else
{
// no camera on this device
return false;
}
}
/**
* Capturing Camera Image will lauch camera app requrest image capture
*/
private void captureImage()
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
/**
* Here we store the file url as it will be null after returning from camera
* app
*/
#Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on scren orientation
// changes
outState.putParcelable("file_uri", fileUri);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}
/**
* Receiving activity result method will be called after closing the camera
*
* */
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE)
{
if (resultCode == RESULT_OK)
{
// successfully captured the image
// display it in image view
previewCapturedImage();
}
else if (resultCode == RESULT_CANCELED)
{
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
}
else
{
// failed to capture image
Toast.makeText(getApplicationContext(),"Sorry! Failed to capture image", Toast.LENGTH_SHORT).show();
}
}
}
/**
* Display image from a path to ImageView
*/
private void previewCapturedImage()
{
try
{
// for open database
Open_Database();
Bitmap bitmap;
try {
bitmap = getImage(fileUri.getPath(),getApplicationContext() );
imagecapture.setImageBitmap(bitmap);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date myDate = new Date();
String realdatetime = dateformat.format(myDate);
Log.e("Current Date","------>"+realdatetime);
mDB_Helper.Insert_MYPHOTOS_Table(mSQLiteDatabase,"title",realdatetime, "description",fileUri.getPath());
// for close database
Close_Database();
}
catch (NullPointerException e)
{
e.printStackTrace();
}
}
public Bitmap getImage(String path,Context con) throws IOException
{
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
int srcWidth = options.outWidth;
int srcHeight = options.outHeight;
int[] newWH = new int[2];
newWH[0] = srcWidth/2;
newWH[1] = (newWH[0]*srcHeight)/srcWidth;
int inSampleSize = 1;
while(srcWidth / 2 >= newWH[0]){
srcWidth /= 2;
srcHeight /= 2;
inSampleSize *= 2;
}
options.inJustDecodeBounds = false;
options.inDither = false;
options.inSampleSize = inSampleSize;
options.inScaled = false;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap sampledSrcBitmap = BitmapFactory.decodeFile(path,options);
ExifInterface exif = new ExifInterface(path);
String s=exif.getAttribute(ExifInterface.TAG_ORIENTATION);
System.out.println("Orientation>>>>>>>>>>>>>>>>>>>>"+s);
Matrix matrix = new Matrix();
float rotation = rotationForImage(con, Uri.fromFile(new File(path)));
if (rotation != 0f) {
matrix.preRotate(rotation);
}
Bitmap pqr=Bitmap.createBitmap(
sampledSrcBitmap, 0, 0, sampledSrcBitmap.getWidth(), sampledSrcBitmap.getHeight(), matrix, true);
return pqr;
}
public float rotationForImage(Context context, Uri uri) {
if (uri.getScheme().equals("content")) {
String[] projection = { Images.ImageColumns.ORIENTATION };
Cursor c = context.getContentResolver().query(
uri, projection, null, null, null);
if (c.moveToFirst()) {
return c.getInt(0);
}
} else if (uri.getScheme().equals("file")) {
try {
ExifInterface exif = new ExifInterface(uri.getPath());
int rotation = (int)exifOrientationToDegrees(
exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL));
return rotation;
} catch (IOException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
}
return 0f;
}
private static float exifOrientationToDegrees(int exifOrientation) {
if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) {
return 90;
} else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) {
return 180;
} else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) {
return 270;
}
return 0;
}
/**
* ------------ Helper Methods ----------------------
* */
/**
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type)
{
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image / video
*/
private static File getOutputMediaFile(int type)
{
File mediaFile = null;
Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
if(isSDPresent)
{
File directory= new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/Mymemoryphotos");
if(!directory.exists())
{
Log.e("Create External Directory","------>");
directory.mkdirs();
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",Locale.getDefault()).format(new Date());
if (type == MEDIA_TYPE_IMAGE)
{
mediaFile = new File(directory.getPath() + File.separator + "IMG_" + timeStamp + ".JPEG");
}
else
{
return null;
}
}
else
{
File directory = contextWrapper.getDir("Mymemoryphotos", Context.MODE_PRIVATE);
if(!directory.exists())
{
Log.e("Create Internal Directory","------>");
directory.mkdirs();
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",Locale.getDefault()).format(new Date());
if (type == MEDIA_TYPE_IMAGE)
{
mediaFile = new File(directory.getPath() + File.separator + "IMG_" + timeStamp + ".JPEG");
}
else
{
return null;
}
}
return mediaFile;
}
}
I want result like this when photo saved in sdcard
My current result when capture image in portrait mode but photo auto
convert to landscape mode
Use ExifInterface to read photo EXIF tags & rotate bitmap when you show it. You may check this for some sample code, however it needs to be edited & cleaned a bit