I am facing a problem while capturing images using intent. The captured image is automatically rotated.
How to prevent the problem. Can someone help?
I hope my solution would still help,
byte[] data = null;
Bitmap bitmap = BitmapFactory.decodeByteArray(fileBytes, 0, fileBytes.length);
ByteArrayOutputStream outputStream = null;
try {
bitmap = ImageResizer.rotateImageIfRequired(bitmap, context, uri);
outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
data = outputStream.toByteArray();
} catch (IOException e) {
Timber.e(e.getMessage());
e.printStackTrace();
} finally {
try {
if (outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
// Intentionally blank
}
}
return data;
}
public static Bitmap rotateImageIfRequired(Bitmap img, Context context, Uri selectedImage) throws IOException {
if (selectedImage.getScheme().equals("content")) {
String[] projection = { MediaStore.Images.ImageColumns.ORIENTATION };
Cursor c = context.getContentResolver().query(selectedImage, projection, null, null, null);
if (c.moveToFirst()) {
final int rotation = c.getInt(0);
c.close();
return rotateImage(img, rotation);
}
return img;
} else {
ExifInterface ei = new ExifInterface(selectedImage.getPath());
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
Timber.d("orientation: %s", orientation);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
return rotateImage(img, 90);
case ExifInterface.ORIENTATION_ROTATE_180:
return rotateImage(img, 180);
case ExifInterface.ORIENTATION_ROTATE_270:
return rotateImage(img, 270);
default:
return img;
}
}
}
private static Bitmap rotateImage(Bitmap img, int degree) {
Matrix matrix = new Matrix();
matrix.postRotate(degree);
Bitmap rotatedImg = Bitmap.createBitmap(img, 0, 0, img.getWidth(), img.getHeight(), matrix, true);
return rotatedImg;
}
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 am selecting an image from gallery and showing it on a image view. Image is getting selected, but on samsung phones it has issue of rotating the image so to solve that I am checking if the image is rotated or not usif EXIF interface and if rotated change its angle.
But this is not working for some images. Some images I can see straight, but some images if they are straight then also they are getting rotate.
As I did debug the orientation for the image is 0, it goes in the default case and applies normal bitmap to the rotated bitmap. Still the image I see is rotated. Not getting why is this happening..
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm=null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bm = Bitmap.createScaledBitmap(bm,512,512, true);
bm.compress(Bitmap.CompressFormat.PNG,100, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".png");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
loadImageFromFile(destination.getAbsolutePath());
}
public void loadImageFromFile(String imageFile){
try {
ExifInterface ei = new ExifInterface(imageFile);
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED);
Bitmap bitmap = BitmapFactory.decodeFile(imageFile);
Bitmap rotatedBitmap = null;
Log.e("orientation",String.valueOf(orientation)+" check");
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
rotatedBitmap = rotateImage(bitmap, 90);
Log.e("orientation",String.valueOf(orientation)+" check");
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotatedBitmap = rotateImage(bitmap, 180);
Log.e("orientation",String.valueOf(orientation)+" check");
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotatedBitmap = rotateImage(bitmap, 270);
Log.e("orientation",String.valueOf(orientation)+" check");
break;
case ExifInterface.ORIENTATION_NORMAL:
rotatedBitmap = bitmap;
Log.e("orientation",String.valueOf(orientation)+" check");
break;
default:
rotatedBitmap = bitmap;
Log.e("orientation",String.valueOf(orientation)+" check");
break;
}
if(rotatedBitmap != null)
{
profile_image.setImageBitmap(rotatedBitmap);
selectedBitmap = rotatedBitmap;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
selectedBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); //replace 100 with desired quality percentage.
byte[] byteArray = stream.toByteArray();
File tempFile = File.createTempFile("temp",null, getCacheDir());
FileOutputStream fos = new FileOutputStream(tempFile);
fos.write(byteArray);
mProfileImage = tempFile;
}
}
catch (IOException ex) {
// UiUtils.showAlert(getString(R.string.error),NewGroupAcvitity.this);
}
}
public static Bitmap rotateImage(Bitmap source, float angle) {
Matrix matrix = new Matrix();
matrix.postRotate(angle);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix,
true);
}
EDIT:
-
#SuppressWarnings("deprecation")
- private void onSelectFromGalleryResult(Intent data) {
-
- Uri uri = (Uri)data.getData();
- String[] filePathColumn = { MediaStore.Images.Media.DATA };
- Cursor cursor = getContentResolver().query(uri,filePathColumn, null, null, null);
- if(cursor != null) {
- cursor.moveToFirst();
- int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
- String picturePath = cursor.getString(columnIndex);
- cursor.close();
-
- loadImageFromFile(picturePath);
- }
- }
#greenapps - use selected file like this? I tried this, but this was not working in xiaomi devices so I changed the code. Is there any other way for other devices?
What's going wrong here? Can anyone help please? Thank you.
loadImageFromFile(destination.getAbsolutePath());
The image that you try to load is originally from a bitmap which you compressed to jpg and saved to file. destination is the File object for that file.
Bitmaps do not contain exif information. And hence your jpg file will not contain an exif too.
So it is useless to use ExifInterface on it.
Sid i saw this code before. And told the same story. Maybe it was even you which i told it.
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == getActivity().RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
String wholeID = DocumentsContract.getDocumentId(filePath);
// 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 = getActivity().getContentResolver().
query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{id}, null);
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
uploadFilePath = cursor.getString(columnIndex);
uploadFilePath = decodeFile(uploadFilePath, 512, 512);
}
cursor.close();
try {
bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), filePath);
if(sendImageType.equals("profile")){
imgProfile.setImageBitmap(bitmap);
}
else if(sendImageType.equals("cover")){
imgCover.setImageBitmap(bitmap);
}
pDialog = ProgressDialog.show(getActivity(), "", "Uploading file...", true);
new Thread(new Runnable() {
public void run() {
uploadFile(uploadFilePath);
}
}).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Decode File :
private String decodeFile(String path,int DESIREDWIDTH, int DESIREDHEIGHT) {
String strMyImagePath = null;
Bitmap scaledBitmap = null;
try {
// Part 1: Decode image
Bitmap unscaledBitmap = ScalingUtilities.decodeFile(path, DESIREDWIDTH, DESIREDHEIGHT, ScalingUtilities.ScalingLogic.FIT);
if (!(unscaledBitmap.getWidth() <= DESIREDWIDTH && unscaledBitmap.getHeight() <= DESIREDHEIGHT)) {
// Part 2: Scale image
scaledBitmap = ScalingUtilities.createScaledBitmap(unscaledBitmap, DESIREDWIDTH, DESIREDHEIGHT, ScalingUtilities.ScalingLogic.FIT);
} else {
unscaledBitmap.recycle();
return path;
}
// Store to tmp file
String extr = Environment.getExternalStorageDirectory().toString();
File mFolder = new File(extr + "/TMMFOLDER");
if (!mFolder.exists()) {
mFolder.mkdir();
}
String s = "tmp.png";
File f = new File(mFolder.getAbsolutePath(), s);
strMyImagePath = f.getAbsolutePath();
FileOutputStream fos = null;
try {
fos = new FileOutputStream(f);
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 75, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
scaledBitmap.recycle();
} catch (Throwable e) {
}
if (strMyImagePath == null) {
return path;
}
return strMyImagePath;
}
Hi, i have an image uploader, i am uploading image from android gallery to my server. But some photos load horizontally. How can i understand, photo is horizontal or vertical and how do i rotate.
It look below, after upload :
to check the orientation of an image
ExifInterface ei = new ExifInterface(photoPath);
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch(orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
break;
case ExifInterface.ORIENTATION_ROTATE_180:
break;
// etc.
}
To rotate the image use
private Bitmap rotateImage(Bitmap source, float angle) {
Bitmap bitmap = null;
Matrix matrix = new Matrix();
matrix.postRotate(angle);
try {
bitmap = Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(),
matrix, true);
} catch (OutOfMemoryError err) {
err.printStackTrace();
}
return bitmap;
}
try this code:
public static Bitmap getOriententionBitmap(String filePath){
Bitmap myBitmap = null;
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);
Bitmap bmp1 = BitmapFactory.decodeStream(new FileInputStream(f), null, null);
myBitmap = Bitmap.createBitmap(bmp1, 0, 0, bmp1.getWidth(), bmp1.getHeight(), mat, true);
}
catch (IOException e) {
Log.w("TAG", "-- Error in setting image");
}
catch(OutOfMemoryError oom) {
Log.w("TAG", "-- OOM Error in setting image");
}
return myBitmap;
}
I made a simple camera application with android. But there is one problem that I cannot solve. My camera app's surfaceView is in portrait mode , however, when I take the image and save the image in the folder. It's not saved in a portrait mode. Since, I'm new to android development I would need some help. I've put some code below.
PictureCallback jpegCallback = new PictureCallback() {
#SuppressWarnings("deprecation")
public void onPictureTaken(byte[] data, Camera camera) {
FileOutputStream outStream = null;
Calendar c = Calendar.getInstance();
File videoDirectory = new File(path);
if (!videoDirectory.exists()) {
videoDirectory.mkdirs();
}
try {
// Write to SD Card
outStream = new FileOutputStream(path + c.getTime().getSeconds() + ".jpg");
outStream.write(data);
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
Bitmap realImage;
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 5;
options.inPurgeable=true; //Tell to gc that whether it needs free memory, the Bitmap can be cleared
options.inInputShareable=true; //Which kind of reference will be used to recover the Bitmap data after being clear, when it will be used in the future
realImage = BitmapFactory.decodeByteArray(data,0,data.length,options);
ExifInterface exif = null;
try {
exif = new ExifInterface(path + c.getTime().getSeconds()
+ ".jpg");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Log.d("EXIF value",
exif.getAttribute(ExifInterface.TAG_ORIENTATION));
if (exif.getAttribute(ExifInterface.TAG_ORIENTATION)
.equalsIgnoreCase("1")) {
realImage = rotate(realImage, 90);
} else if (exif.getAttribute(ExifInterface.TAG_ORIENTATION)
.equalsIgnoreCase("8")) {
realImage = rotate(realImage, 90);
} else if (exif.getAttribute(ExifInterface.TAG_ORIENTATION)
.equalsIgnoreCase("3")) {
realImage = rotate(realImage, 90);
} else if (exif.getAttribute(ExifInterface.TAG_ORIENTATION)
.equalsIgnoreCase("0")) {
realImage = rotate(realImage, 90);
}
} catch (Exception e) {
}
image.setImageBitmap(realImage);
fotoButton.setClickable(true);
camera.startPreview();
progressLayout.setVisibility(View.GONE);
exitButton.setClickable(true);
}
};
public static Bitmap rotate(Bitmap source, float angle) {
Matrix matrix = new Matrix();
matrix.postRotate(angle);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(),
source.getHeight(), matrix, false);
}
try below methods some times some device have orientantion roated to 90 or 180 or 270 here is the methods try this to get image in normal mode if its gets rotated:
public static Bitmap RotateImage(String imagePath, boolean rotateImage) {
Matrix imageMatrix = new Matrix();
if (rotateImage) {
int rotationNeeded = getImageRotationDegrees(imagePath);
if (rotationNeeded != 0) {
imageMatrix.postRotate(rotationNeeded);
}
}
public static int getImageRotationDegrees(String imagePath) {
int currentRotation = getImageOrientation(imagePath);
switch (currentRotation) {
case ExifInterface.ORIENTATION_ROTATE_90:
return 90;
case ExifInterface.ORIENTATION_ROTATE_180:
return 180;
case ExifInterface.ORIENTATION_ROTATE_270:
return 270;
}
return 0;
}
public static int getImageOrientation(String imagePath) {
ExifInterface exifInterface;
try {
exifInterface = new ExifInterface(imagePath);
} catch (IOException e) {
return ExifInterface.ORIENTATION_UNDEFINED;
}
return exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED);
}
pictures taken in vertical format are saved in landscape format and vice-versa. I am using Android camera by using this intent
Intent captureImage = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
captureImage.putExtra(MediaStore.EXTRA_OUTPUT, imageFileUri);
startActivityForResult(captureImage, CAMERA_PIC_REQUEST);
onActivityResult() I am just saving image URL to my database and displaying it in a listview.
but there orientatiuon changes. The same will happen if I choose image from gallery and save it.
I want the orientation in which photo has been taken. I dont want to change it. Is anybody have a solutin on this.
Some devices doesn't rotate image after it was taken but just write its orientation information into Exif data. So before using taken photo you should call method like :
private int resolveBitmapOrientation(File bitmapFile) throws IOException {
ExifInterface exif = null;
exif = new ExifInterface(bitmapFile.getAbsolutePath());
return exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
}
to check its orientation. Then apply:
private Bitmap applyOrientation(Bitmap bitmap, int orientation) {
int rotate = 0;
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;
default:
return bitmap;
}
int w = bitmap.getWidth();
int h = bitmap.getHeight();
Matrix mtx = new Matrix();
mtx.postRotate(rotate);
return Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true);
}
and use this new bitmap in your listview. Or it's even better to call this methods just after your photo was taken and override it with new rotated one.
In case if you are receiving Bitmap data as Uri the following method can be used to retrieve its filepath:
public static String getPathFromURI(Context context, Uri contentUri) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT &&
DocumentsContract.isDocumentUri(context, contentUri)) {
return getPathForV19AndUp(context, contentUri);
} else {
return getPathForPreV19(context, contentUri);
}
}
private static String getPathForPreV19(Context context, Uri contentUri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver().query(contentUri, projection, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
try {
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
return cursor.getString(columnIndex);
} finally {
cursor.close();
}
}
return null;
}
#TargetApi(Build.VERSION_CODES.KITKAT)
private static String getPathForV19AndUp(Context context, Uri contentUri) {
String documentId = DocumentsContract.getDocumentId(contentUri);
String id = documentId.split(":")[1];
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[]{ id }, null);
if (cursor != null) {
try {
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
return cursor.getString(columnIndex);
}
} finally {
cursor.close();
}
}
return null;
}
You can also follow by this way:
static Uri image_uri;
static Bitmap taken_image=null;
image_uri=fileUri; // file where image has been saved
taken_image=BitmapFactory.decodeFile(image_uri.getPath());
try
{
ExifInterface exif = new ExifInterface(image_uri.getPath());
//Since API Level 5
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch(orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
taken_image=decodeScaledBitmapFromSdCard(image_uri.getPath(), 200, 200);
RotateBitmap(taken_image, 90);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
taken_image=decodeScaledBitmapFromSdCard(image_uri.getPath(), 200, 200);
RotateBitmap(taken_image, 180);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
taken_image=decodeScaledBitmapFromSdCard(image_uri.getPath(), 200, 200);
RotateBitmap(taken_image, 270);
break;
case ExifInterface.ORIENTATION_NORMAL:
taken_image=decodeScaledBitmapFromSdCard(image_uri.getPath(), 200, 200);
RotateBitmap(taken_image, 0);
break;
}
}
catch (OutOfMemoryError e)
{
Toast.makeText(getActivity(),e+"\"memory exception occured\"",Toast.LENGTH_LONG).show();
}
public Bitmap RotateBitmap(Bitmap source, float angle) {
Matrix matrix = new Matrix();
matrix.postRotate(angle);
round_Image = source;
round_Image = Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
}