Hello i am resizing the image after capturing from native camera.. image resizing is working fine but i have only one problem and that is the image is getting skewed after resizing.
here is the code that i am using to resize the image.
File f = new File(Environment.getExternalStorageDirectory() + File.separator + "Bavel/" + imageName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(f);
if (orientation == ExifInterface.ORIENTATION_UNDEFINED) {
saveByteArray(fos, getBytesFromBitmap(loadedImage));
} else {
saveByteArrayWithOrientation(fos, getBytesFromBitmap(loadedImage), orientation);
}
} catch (FileNotFoundException e) {
Log.e("Error", "File not found: " + e.getMessage());
} catch (IOException e) {
Log.e("Error", "File write failure: " + e.getMessage());
}
private void saveByteArray(FileOutputStream fos, byte[] data) throws IOException {
long time = System.currentTimeMillis();
fos.write(data);
Log.e("saveByteArray: %1dms", "" + (System.currentTimeMillis() - time));
}
private void saveByteArrayWithOrientation(FileOutputStream fos, byte[] data, int orientation) {
long totalTime = System.currentTimeMillis();
long time = System.currentTimeMillis();
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
Log.e("decodeByteArray: %1dms", "" + (System.currentTimeMillis() - time));
time = System.currentTimeMillis();
if (orientation != 0 && bitmap.getWidth() > bitmap.getHeight()) {
Matrix matrix = new Matrix();
matrix.postRotate(orientation);
int newWidth;
int newHeight;
if (bitmap.getWidth() > bitmap.getHeight()) {
newHeight = Helper.BITMAP_HEIGHT;
newWidth = Helper.BITMAP_HEIGHT * bitmap.getWidth() / bitmap.getHeight();
} else {
newWidth = Helper.BITMAP_HEIGHT;
newHeight = Helper.BITMAP_HEIGHT * bitmap.getHeight() / bitmap.getWidth();
}
bitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, false);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
time = System.currentTimeMillis();
bitmap.compress(Bitmap.CompressFormat.JPEG, Helper.COMPRESS_QUALITY, fos);
Log.d("compress: %1dms", "" + (System.currentTimeMillis() - time));
Log.d("bitmap height ", "" + bitmap.getHeight());
Log.d("bitmap witdh ", "" + bitmap.getWidth());
bitmap.recycle();
Log.d("saveByte: %1dms", "" + (System.currentTimeMillis() - totalTime));
}
public byte[] getBytesFromBitmap(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, Helper.COMPRESS_QUALITY, stream);
return stream.toByteArray();
}
Here is the output after resizing the image
But i want the out put like this
Please help and thank for help in advance.
I have solved this by using below code. i am adding the answer so it might be helpful to someone else.
ExifInterface exif = new ExifInterface(imagePath);
final int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
File root = new File(Environment.getExternalStorageDirectory(), "/Bavel/");
if (!root.exists()) {
root.mkdirs();
}
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "Bavel/" + imageName);
resizeNewImage(loadedImage, f, orientation);
private void resizeNewImage(Bitmap bm, File file, int orientation) {
try {
if (bm.getWidth() > bm.getHeight()) {
int newWidth;
int newHeight;
if (bm.getWidth() > bm.getHeight()) {
newHeight = Helper.BITMAP_HEIGHT;
newWidth = Helper.BITMAP_HEIGHT * bm.getWidth() / bm.getHeight();
} else {
newWidth = Helper.BITMAP_HEIGHT;
newHeight = Helper.BITMAP_HEIGHT * bm.getHeight() / bm.getWidth();
}
Matrix matrix = new Matrix();
switch (orientation) {
case ExifInterface.ORIENTATION_NORMAL:
matrix.postRotate(90);
case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
matrix.setScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
matrix.setRotate(180);
break;
case ExifInterface.ORIENTATION_FLIP_VERTICAL:
matrix.setRotate(180);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_TRANSPOSE:
matrix.setRotate(90);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_90:
matrix.setRotate(90);
break;
case ExifInterface.ORIENTATION_TRANSVERSE:
matrix.setRotate(-90);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
matrix.setRotate(-90);
break;
default:
matrix.postRotate(90);
}
bm = Bitmap.createScaledBitmap(bm, newWidth, newHeight, true);
bm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
// file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.JPEG, Helper.COMPRESS_QUALITY, ostream);
ostream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Related
In My app the User captures an image from the gallery or camera it is then converted to PDF, Now my problem is that images captured from the samsung devices are rotated,
I am trying to edit the exif data but it does not work,
there is no errors the image just stays rotated
I am new to android and the entire EXIF data thing goes over my head, some advice would be awesome
private void PDFCreation(){
PdfDocument document=new PdfDocument();
PdfDocument.PageInfo pageInfo;
PdfDocument.Page page;
Canvas canvas;
int i;
for (i=0; i < list.size(); i++) {
pageInfo=new PdfDocument.PageInfo.Builder(992, 1432, 1).create();
page=document.startPage(pageInfo);
canvas=page.getCanvas();
image=BitmapFactory.decodeFile(list.get(i));
image=Bitmap.createScaledBitmap(image, 980, 1420, true);
image.setDensity(DisplayMetrics.DENSITY_300);
canvas.setDensity(DisplayMetrics.DENSITY_300);
ExifInterface exif;
int rotate = 0;
try
{
exif = new ExifInterface(selectedPhoto);
int exifOrientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (exifOrientation)
{
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
}
if (rotate != 0)
{
int w = image.getWidth();
int h = image.getHeight();
// Setting pre rotate
Matrix mtx = new Matrix();
mtx.preRotate(rotate);
// Rotating Bitmap & convert to ARGB_8888, required by tess
try
{
image = Bitmap.createBitmap(image, 0, 0, w, h, mtx, false);
}
catch(OutOfMemoryError e)
{
e.printStackTrace();
//image = Bitmap.createBitmap(image, 0, 0, w/2, h/2, mtx, false);
}
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
Matrix matrix = new Matrix();
matrix.postRotate(rotate);
image=createBitmap(image, 0, 0,
image.getWidth(), image.getHeight(),
matrix, true);
canvas.drawBitmap(image, 0, 0, null);
document.finishPage(page);
}
#SuppressWarnings("deprecation") String directory_path=Environment.getExternalStorageDirectory().getPath() + "/mypdf/";
File file=new File(directory_path);
if (!file.exists()) {
//noinspection ResultOfMethodCallIgnored
file.mkdirs();
}
#SuppressLint("SimpleDateFormat") String timeStamp=(new SimpleDateFormat("yyyyMMdd_HHmmss")).format(new Date());
String targetPdf=directory_path + timeStamp + ".pdf";
filePath=new File(targetPdf);
try {
document.writeTo(new FileOutputStream(filePath));
} catch (IOException e) {
Log.e("main", "error " + e.toString());
Toasty.error(this, "Error making PDF" + e.toString(), Toast.LENGTH_LONG).show();
}
document.close();
}
Currently I'm using mulitpart/form-data for uploading images to server . In node.js server side the images are being stored without any problem . But it's taking a lot of time to upload the pictures to server . I tried to rescale bitmaps before uploading them but in most of the cases pictures are being uploaded in a larger size than the original image for ex- 200kb pic is becoming 400kb something like that . So, I wonder How to scale bitmaps properly and upload them to server in good quality with efficient speed ?
Bitmap Scaling Code:
bmp = MediaStore.Images.Media.getBitmap(ctx.getContentResolver(), uri);
int maxSize=700;
int outWidth;
int outHeight;
int inWidth = bmp.getWidth();
int inHeight = bmp.getHeight();
if(inWidth > inHeight){
outWidth = maxSize;
outHeight = (inHeight * maxSize) / inWidth;
} else {
outHeight = maxSize;
outWidth = (inWidth * maxSize) / inHeight;
}
final Bitmap new_bitmap = Bitmap.createScaledBitmap(bmp, outWidth, outHeight, false);
Saving Bitmap to storage:
void saveImage(String imgName, Bitmap bm) throws IOException {
//Create Path to save Image
File file_path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES + "/Infinity"); //Creates app specific folder
file_path.mkdirs();
File imageFile = new File(file_path, imgName + ".png"); // Imagename.png
FileOutputStream out = new FileOutputStream(imageFile);
try {
bm.compress(Bitmap.CompressFormat.PNG, 100, out); // Compress Image
out.flush();
out.close();
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(ctx, new String[]{imageFile.getAbsolutePath()}, null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String pathi, Uri uri) {
Log.i("ExternalStorage", "Scanned " + file_path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
parts.add(prepareFilePart("photo", pathi));
RequestBody description = createPartFromString(obji.toString());
FileUploadService service = ServiceGenerator.createService(FileUploadService.class);
Call<ResponseBody> call = service.uploadMultipleFilesDynamic(description, parts);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call,
Response<ResponseBody> response) {
Log.v("Upload", "success");
Intent i=new Intent(ctx,Home_Screen.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(i);
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
if(t.getMessage()!=null) {
Log.e("Upload error:", t.getMessage());
Toast.makeText(ctx, t.getMessage(), Toast.LENGTH_LONG).show();
//Don't toast t.getMessage it would show the ip address which is bad
}
}
});
//Toast.makeText(ctx, "Downloaded Successfully", Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
throw new IOException();
}
}
Try this, it's a working solution.
private uploadPostImage(String imagePath) throws Exception {
String orientation = "Portrait";
Bitmap bm = null;
try {
bm = checkForRotation(imagePath);
if (bm.getHeight() > bm.getWidth()) {
orientation = "Portrait";
} else if (bm.getWidth() > bm.getHeight()) {
orientation = "Landscape";
} else {
orientation = "Portrait";
}
} catch (Exception e) {
Log.e(e.getClass().getName(), e.getMessage());
}
if(bm.getWidth()>1000)
{
bm = getResizedBitmap(bm,1000);
}
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
/*
/....
Multipart uploading work
..../
*/
} catch (Exception e) {
Log.e(e.getClass().getName(), e.getMessage());
}
}
public Bitmap checkForRotation(String filename) {
Bitmap bitmap = BitmapFactory.decodeFile(filename);
int tmpHeight, tmpWidth;
tmpWidth = bitmap.getWidth();
tmpHeight = bitmap.getHeight();
if (tmpWidth > tmpHeight)
{
tmpWidth = 1000;
tmpHeight = (bitmap.getHeight() * tmpWidth) / bitmap.getWidth();
} else
{
tmpHeight = 1000;
tmpWidth = (bitmap.getWidth() * tmpHeight) / bitmap.getHeight();
}
bitmap= Bitmap.createScaledBitmap(bitmap, tmpWidth, tmpHeight, true);
ExifInterface ei = null;
try {
ei = new ExifInterface(filename);
new ExifInterface(filename);
} catch (IOException e) {
e.printStackTrace();
}
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
bitmap = rotateImage(bitmap, 90);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
bitmap = rotateImage(bitmap, 180);
break;
}
return bitmap;
}
public Bitmap getResizedBitmap(Bitmap bm, int newWidth) {
int width = bm.getWidth();
int height = bm.getHeight();
float ratio = (float)width/(float)height;
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float)newWidth/ratio) / height;
// CREATE A MATRIX FOR THE MANIPULATION
Matrix matrix = new Matrix();
// RESIZE THE BIT MAP
matrix.postScale(scaleWidth, scaleHeight);
// RECREATE THE NEW BITMAP
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height,
matrix, false);
return resizedBitmap;
}
Here is a method to compress the image. First send the path of the image you want to compress to this method. It will return you the compress image path, then make a file from that path and upload.
public static String compressImage(String filePath) {
try {
//String filePath = getRealPathFromURI(imageUri);
Bitmap scaledBitmap = null;
BitmapFactory.Options options = new BitmapFactory.Options();
//by setting this field as true, the actual bitmap pixels are not loaded in the memory. Just the bounds are loaded. If
//you try the use the bitmap here, you will get null.
options.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeFile(filePath, options);
int actualHeight = options.outHeight;
int actualWidth = options.outWidth;
//max Height and width values of the compressed image is taken as 816x612
float maxHeight = 816.0f;
float maxWidth = 612.0f;
float imgRatio = actualWidth / actualHeight;
float maxRatio = maxWidth / maxHeight;
//width and height values are set maintaining the aspect ratio of the image
if (actualHeight > maxHeight || actualWidth > maxWidth) {
if (imgRatio < maxRatio) {
imgRatio = maxHeight / actualHeight;
actualWidth = (int) (imgRatio * actualWidth);
actualHeight = (int) maxHeight;
} else if (imgRatio > maxRatio) {
imgRatio = maxWidth / actualWidth;
actualHeight = (int) (imgRatio * actualHeight);
actualWidth = (int) maxWidth;
} else {
actualHeight = (int) maxHeight;
actualWidth = (int) maxWidth;
}
}
//setting inSampleSize value allows to load a scaled down version of the original image
options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);
//inJustDecodeBounds set to false to load the actual bitmap
options.inJustDecodeBounds = false;
//this options allow android to claim the bitmap memory if it runs low on memory
options.inPurgeable = true;
options.inInputShareable = true;
options.inTempStorage = new byte[16 * 1024];
try {
//load the bitmap from its path
bmp = BitmapFactory.decodeFile(filePath, options);
} catch (OutOfMemoryError exception) {
exception.printStackTrace();
}
try {
scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.ARGB_8888);
} catch (OutOfMemoryError exception) {
exception.printStackTrace();
}
float ratioX = actualWidth / (float) options.outWidth;
float ratioY = actualHeight / (float) options.outHeight;
float middleX = actualWidth / 2.0f;
float middleY = actualHeight / 2.0f;
Matrix scaleMatrix = new Matrix();
scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);
Canvas canvas = new Canvas(scaledBitmap);
canvas.setMatrix(scaleMatrix);
canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));
//check the rotation of the image and display it properly
ExifInterface exif;
try {
exif = new ExifInterface(filePath);
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0);
Log.d("EXIF", "Exif: " + orientation);
Matrix matrix = new Matrix();
if (orientation == 6) {
matrix.postRotate(90);
Log.d("EXIF", "Exif: " + orientation);
} else if (orientation == 3) {
matrix.postRotate(180);
Log.d("EXIF", "Exif: " + orientation);
} else if (orientation == 8) {
matrix.postRotate(270);
Log.d("EXIF", "Exif: " + orientation);
}
scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0,
scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix,
true);
} catch (IOException e) {
e.printStackTrace();
}
FileOutputStream out = null;
//String filename = getFilename();
String filename = getFilename();
try {
out = new FileOutputStream(filename);
//write the compressed bitmap at the destination specified by filename.
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return filename;
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
use multipart to upload images with retrofit instead of any other network library.
How to make images upload faster in an Android app?
BitmapFactory.Options opts = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opts);
bitmap = Bitmap.createScaledBitmap(bitmap, 150, 50, false);
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int newWidth = 150;
int newHeight = 50;
// calculate the scale - in this case = 0.4f
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// createa matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// rotate the Bitmap
matrix.postRotate(-90);
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
width, height, matrix, true);
// HomePage.image.setImageBitmap(resizedBitmap);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
resizedBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Intent in1 = new Intent(CameraView.this, ImageDisplay.class);
in1.putExtra("picture",byteArray);
startActivity(in1);
This is my code. I am unable to set image because image becomes stretched. It's not coming clear image full screen. Where am I doing wrong?
My image come like this we have fix it it should not stretched.
It can be due to 'createScaledBitmap' as may be the image size is small and when you try to resize it it gets streched
You can use this:
public Bitmap compressImage(String imageUri) {
String filePath = getRealPathFromURI(imageUri);
Bitmap scaledBitmap = null;
BitmapFactory.Options options = new BitmapFactory.Options();
// by setting this field as true, the actual bitmap pixels are not loaded in the memory. Just the bounds are loaded. If
// you try the use the bitmap here, you will get null.
options.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeFile(filePath, options);
int actualHeight = options.outHeight;
int actualWidth = options.outWidth;
// max Height and width values of the compressed image is taken as 816x612
float maxHeight = 816.0f;
float maxWidth = 612.0f;
float imgRatio = actualWidth / actualHeight;
float maxRatio = maxWidth / maxHeight;
// width and height values are set maintaining the aspect ratio of the image
if (actualHeight > maxHeight || actualWidth > maxWidth) {
if (imgRatio < maxRatio) {
imgRatio = maxHeight / actualHeight;
actualWidth = (int) (imgRatio * actualWidth);
actualHeight = (int) maxHeight;
} else if (imgRatio > maxRatio) {
imgRatio = maxWidth / actualWidth;
actualHeight = (int) (imgRatio * actualHeight);
actualWidth = (int) maxWidth;
} else {
actualHeight = (int) maxHeight;
actualWidth = (int) maxWidth;
}
}
// setting inSampleSize value allows to load a scaled down version of the original image
options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);
// inJustDecodeBounds set to false to load the actual bitmap
options.inJustDecodeBounds = false;
// this options allow android to claim the bitmap memory if it runs low on memory
options.inPurgeable = true;
options.inInputShareable = true;
options.inTempStorage = new byte[16 * 1024];
try {
// load the bitmap from its path
bmp = BitmapFactory.decodeFile(filePath, options);
} catch (OutOfMemoryError exception) {
exception.printStackTrace();
}
try {
scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.ARGB_8888);
} catch (OutOfMemoryError exception) {
exception.printStackTrace();
}
float ratioX = actualWidth / (float) options.outWidth;
float ratioY = actualHeight / (float) options.outHeight;
float middleX = actualWidth / 2.0f;
float middleY = actualHeight / 2.0f;
Matrix scaleMatrix = new Matrix();
scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);
Canvas canvas = new Canvas(scaledBitmap);
canvas.setMatrix(scaleMatrix);
canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));
// check the rotation of the image and display it properly
ExifInterface exif;
try {
exif = new ExifInterface(filePath);
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION, 0);
Log.d("EXIF", "Exif: " + orientation);
Matrix matrix = new Matrix();
if (orientation == 6) {
matrix.postRotate(90);
Log.d("EXIF", "Exif: " + orientation);
} else if (orientation == 3) {
matrix.postRotate(180);
Log.d("EXIF", "Exif: " + orientation);
} else if (orientation == 8) {
matrix.postRotate(270);
Log.d("EXIF", "Exif: " + orientation);
}
scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0,
scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix,
true);
} catch (IOException e) {
e.printStackTrace();
}
return scaledBitmap;
}
Code for saving:
FileOutputStream outStream = null;
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + "/camtest");
dir.mkdirs();
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
outStream = new FileOutputStream(outFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
refreshGallery(outFile);
Permissions:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Finally:
Go to Device Settings>Device>Applications>Application Manager>"your app">Permissions>Enable Storage permission!
I have a written a code to pick image from gallery or capture image from camera you can use this to achieve what you want and you will get the file path of capture from camera or picked from gallery image file path in onactivityforResult
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;
private static final int CROP_FROM_CAMERA = 2;
private static final int PICK_FROM_FILE = 3;
public static final int camPermissionRequestCode=6;
public static final int galleryPermissionRequestCode=4;
private Uri imageUri;
private File profilePicPicked;
#Override
public void onClick(View v) {
int id=v.getId();
switch (id){
case R.id.camera:
if (Build.VERSION.SDK_INT >= 23) {
//do your check here
isStoragePermissionGranted(camPermissionRequestCode);
} else {
captureImage();
}
break;
case R.id.upload_image:
if (Build.VERSION.SDK_INT >= 23) {
//do your check here
isStoragePermissionGranted(galleryPermissionRequestCode);
} else {
pickFromGallery();
}
break;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (resultCode != Activity.RESULT_OK)
return;
switch (requestCode) {
case CAMERA_CAPTURE_IMAGE_REQUEST_CODE:
/**
* After taking a picture, do the crop
*/
File file2 = handleImageUri(imageUri,getContext());
try {
ExifInterface ei = new ExifInterface(file2.getAbsolutePath());
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
file2=rotateImage(file2, 90);
/* Toast.makeText(getActivity(),"90",Toast.LENGTH_SHORT).show();*/
break;
case ExifInterface.ORIENTATION_ROTATE_180:
file2=rotateImage(file2, 180);
/* Toast.makeText(getActivity(),"180",Toast.LENGTH_SHORT).show();*/
break;
case ExifInterface.ORIENTATION_ROTATE_270:
file2=rotateImage(file2, 270);
/* Toast.makeText(getActivity(),"270",Toast.LENGTH_SHORT).show();*/
break;
case ExifInterface.ORIENTATION_NORMAL:
/*Toast.makeText(getActivity(),"default",Toast.LENGTH_SHORT).show();*/
default:
break;
}
}catch (Exception e){
e.printStackTrace();
}
profilePicPicked= file2;
break;
case PICK_FROM_FILE:
/**
* After selecting image from files, save the selected path
*/
/*Toast.makeText(getContext(), "Image Taken", Toast.LENGTH_LONG).show();*/
imageUri = data.getData();
//iv_post.setImageURI(fileUri);
File fileGAllr = getRealPathFromURIForGallery(getActivity(),imageUri);
profilePicPicked=fileGAllr;
// new Updata().execute("");
// btn_gallery.setVisibility(View.GONE);
break;
case CROP_FROM_CAMERA:
break;
}
}
public static File getRealPathFromURIForGallery(Context context, Uri uri) {
File file = null;
try {
String extension="";
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = context.getContentResolver().query(uri, filePathColumn, null, null, null);
if (cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
extension= filePath.substring(filePath.lastIndexOf("."));
System.out.print("");
}
cursor.close();
InputStream input = null;
input = context.getContentResolver().openInputStream(uri);
if (input == null) {
return null;
}
file = new File(context.getCacheDir(), System.currentTimeMillis()+"_Photo"+extension);
OutputStream output = new FileOutputStream(file);
try {
byte[] buffer = new byte[4 * 1024];
int read;
while ((read = input.read(buffer)) != -1) {
output.write(buffer, 0, read);
}
output.flush();
} finally {
output.close();
input.close();
}
} catch (IOException e) {
Log.d("Error", e.toString());
}
return file;
}
public File rotateImage(File f, float angle) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap source = BitmapFactory.decodeFile(f.getAbsolutePath(), options);
Matrix matrix = new Matrix();
matrix.postRotate(angle);
Bitmap finalBm= Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
File editedFile=getOutputMediaFile(MEDIA_TYPE_IMAGE);
FileOutputStream out = null;
try {
out = new FileOutputStream(editedFile);
finalBm.compress(Bitmap.CompressFormat.JPEG, 100, out); // bmp is your Bitmap instance
// PNG is a lossless format, the compression factor (100) is ignored
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
f.delete();
return editedFile;
}
public static File handleImageUri(Uri uri, Context context) {
Pattern pattern = Pattern.compile("(content://media/.*\\d)");
Matcher matcher = pattern.matcher(uri.getPath());
if (matcher.find()) {
return getRealPathFromURI(context, uri);
} else {
return new File(uri.getPath());
}
}
public static File getRealPathFromURI(Context context, Uri uri) {
File file = null;
try {
InputStream input = null;
input = context.getContentResolver().openInputStream(uri);
if (input == null) {
return null;
}
file = new File(context.getCacheDir(), System.currentTimeMillis()+"Photo.png");
OutputStream output = new FileOutputStream(file);
try {
byte[] buffer = new byte[4 * 1024];
int read;
while ((read = input.read(buffer)) != -1) {
output.write(buffer, 0, read);
}
output.flush();
} finally {
output.close();
input.close();
}
} catch (IOException e) {
Log.d("Error", e.toString());
}
return file;
}
public boolean isStoragePermissionGranted(int requsetCode) {
if (Build.VERSION.SDK_INT >= 23) {
if (ContextCompat.checkSelfPermission(getActivity(),android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
if(requsetCode==camPermissionRequestCode){
captureImage();
}else{
pickFromGallery();
}
return true;
} else {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requsetCode);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
if(requsetCode==camPermissionRequestCode){
captureImage();
}else{
pickFromGallery();
}
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
if(requestCode==camPermissionRequestCode){
captureImage();
}else if(requestCode==galleryPermissionRequestCode){
pickFromGallery();
}
//resume tasks needing this permission
}
}
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
imageUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
private void pickFromGallery(){
Intent i = new Intent(
Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, PICK_FROM_FILE);
}
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
private File getOutputMediaFile(int type) {
// TODO Auto-generated method stub
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"marcopolo");
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
> public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight){
> final int height = options.outHeight;
> final int width = options.outWidth;
> int inSampleSize = 1;
> if (height > reqHeight || width > reqWidth) {final int heightRatio = Math.round((float) height / (float) reqHeight);
> final int widthRatio = Math.round((float) width / (float) reqWidth);
> inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;}
> final float totalPixels = width * height;
> final float totalReqPixelsCap = reqWidth * reqHeight * 2;
> while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {inSampleSize++;}
> return inSampleSize;}
>
> > `Blockquote`
I am creating one app which uses camera. camera is perfectly working in both landscape and portrait. But the Result Image is perfectly set with in the frame at the landscape mode. but in portrait , the result image set in the frame at 90 degree orientaion.how to fix this problem?
public void createImageInImageCenter() {
Bitmap backgroundBitmap = DgCamActivity.photo;
backgroundBitmap = backgroundBitmap.createScaledBitmap(
backgroundBitmap, 900, 700, true);
Bitmap bitmapToDrawInTheCenter = null;
File f = new File(FrameGridView.selected_img);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
try {
bitmapToDrawInTheCenter = BitmapFactory.decodeStream(
new FileInputStream(f), null, options);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
bitmapToDrawInTheCenter = bitmapToDrawInTheCenter.createScaledBitmap(
bitmapToDrawInTheCenter, 900, 700, true);
resultBitmap = Bitmap.createBitmap(backgroundBitmap.getWidth(),
backgroundBitmap.getHeight(), backgroundBitmap.getConfig());
Canvas canvas = new Canvas(resultBitmap);
canvas.drawBitmap(backgroundBitmap, new Matrix(), null);
canvas.drawBitmap(bitmapToDrawInTheCenter, 0, 0, new Paint());
ImageView image = (ImageView) findViewById(R.id.final_img);
image.setImageBitmap(resultBitmap);
}
Please try below code it's helpful to you for handle image rotation.
public class CaptureImage extends Activity {
private static final int PICK_CAMERA_IMAGE = 2;
ImageView img;
Button btn;
double d = 1.2;
private Uri mImageCaptureUri;
public static String userPicPath;
File file;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_capture_image);
img = (ImageView) findViewById(R.id.activity_capture_image_img);
btn = (Button) findViewById(R.id.button1);
btn.setText(String.valueOf(d));
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
SimpleDateFormat dateFormatter = new SimpleDateFormat(
"yyyyMMdd_HHmmss", Locale.US);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
file = new File(Environment.getExternalStorageDirectory()
+ "/MyImage", "img_"
+ dateFormatter.format(new Date()).toString() + ".png");
userPicPath = file.getPath();
mImageCaptureUri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
startActivityForResult(intent, PICK_CAMERA_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_CAMERA_IMAGE && resultCode == RESULT_OK) {
Log.d("CaptureImage", mImageCaptureUri.toString());
Bitmap bitmapProfile = getBitmap(userPicPath, this);
img.setImageBitmap(rotatedBitmap(file, bitmapProfile));
}
}
public static Bitmap rotatedBitmap(File imageFile, Bitmap source) {
try {
int rotate = 0;
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.v("Capture Image", "Exif orientation: " + orientation + ":"
+ String.valueOf(rotate));
Matrix matrix = new Matrix();
matrix.postRotate(rotate);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(),
source.getHeight(), matrix, false);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static Bitmap getBitmap(String path, Context context) {
Uri uri = Uri.fromFile(new File(path));
InputStream in = null;
ContentResolver mContentResolver = context.getContentResolver();
try {
// final int IMAGE_MAX_SIZE = 2048;
final int IMAGE_MAX_SIZE = 1024;
in = mContentResolver.openInputStream(uri);
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, o);
in.close();
int scale = 1;
if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
scale = (int) Math.pow(
2,
(int) Math.round(Math.log(IMAGE_MAX_SIZE
/ (double) Math.max(o.outHeight, o.outWidth))
/ Math.log(0.5)));
}
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
in = mContentResolver.openInputStream(uri);
Bitmap b = BitmapFactory.decodeStream(in, null, o2);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 25, stream);
in.close();
return b;
} catch (FileNotFoundException e) {
Log.e("CaptureImage", "file " + path + " not found");
} catch (IOException e) {
Log.e("CaptureImage", "file " + path + " not found");
}
return null;
}
}
and layout file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Capture Image" />
<ImageView
android:id="#+id/activity_capture_image_img"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitCenter"
android:src="#drawable/ic_launcher" />
I came across the same problem. Before Android API 13, the retrived image from the camera was the same that the preview one, but after API 13 they have inverted the Y axis from the preview. It is the "real" view from the point of the camera. Apply this function to your bitmap :
public Bitmap rotateBitmap(Bitmap source) {
orientation = getActivity().getWindowManager().getDefaultDisplay().getRotation();
Matrix matrix = new Matrix();
if(android.os.Build.VERSION.SDK_INT > 13) {
float[] mirrorY = {-1, 0, 0, 0, 1, 0, 0, 0, 1};
Matrix matrixMirrorY = new Matrix();
matrixMirrorY.setValues(mirrorY);
matrix.postConcat(matrixMirrorY);
}
switch (orientation) {
case Surface.ROTATION_0:
if(android.os.Build.VERSION.SDK_INT > 13) {
matrix.postRotate(90);
} else {
matrix.postRotate(270);
}
break;
case Surface.ROTATION_90:
matrix.postRotate(0);
break;
case Surface.ROTATION_180:
if(android.os.Build.VERSION.SDK_INT > 13) {
matrix.postRotate(270);
} else {
matrix.postRotate(90);
}
break;
case Surface.ROTATION_270:
matrix.postRotate(180);
break;
}
return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
}
This is for processing the image or saving it to the sdcard for example. But if the rotation problem occurs in your preview, use this rotation in your "surfaceChanged" method :
Camera.Parameters parameters = mCamera.getParameters();
orientation = getActivity().getWindowManager().getDefaultDisplay().getRotation();
switch (orientation) {
case Surface.ROTATION_0:
mCamera.setDisplayOrientation(90);
break;
case Surface.ROTATION_90:
mCamera.setDisplayOrientation(0);
break;
case Surface.ROTATION_180:
mCamera.setDisplayOrientation(270);
break;
case Surface.ROTATION_270:
mCamera.setDisplayOrientation(180);
break;
}
Tested and working on Android 4.x (AOSP, Cyanogen, and FirePhone).
Hello I am working on one android app where I need to capture the image using camera intent and set the bitmap in the imageview but here bitmap is rotated by 90 degree. I have checked many threads of stackoverflow like Photo rotate 90 degree while capture in some phones but did not work for me.
Here when I am executing this exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1); then it is returning 0 ORIENTATION_UNDEFINED and in my getImage function no condition is satisfying.
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
capturedPhotoName = System.currentTimeMillis() + ".png";
File photo = new File(Environment.getExternalStorageDirectory(),
capturedPhotoName);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
startActivityForResult(cameraIntent, CAMERA_INTENT_REQUEST);
onActivityResult
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr,
selectedImage);
bitmap = Util.getImage(bitmap, selectedImage.toString());
mPictureImageView.setImageBitmap(bitmap);
} catch (Exception e) {
Log.e("New Issue Activity", e.toString());
}
/**
* Get the image orientation
*
* #param imagePath
* #return orietation angle
* #throws IOException
*/
public static Bitmap getImage(Bitmap bitmap, String path) throws IOException {
Matrix m = new Matrix();
ExifInterface exif = new ExifInterface(path);
int orientation = exif
.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
if ((orientation == ExifInterface.ORIENTATION_ROTATE_180)) {
m.postRotate(180);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
bitmap.getHeight(), m, true);
return bitmap;
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
m.postRotate(90);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
bitmap.getHeight(), m, true);
return bitmap;
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
m.postRotate(270);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
bitmap.getHeight(), m, true);
return bitmap;
}
return bitmap;
}
I implemented one photo take activity which you can take the photo and set the orientation of the photo. It is supported by every device I tested including Samsung galaxy series, tablets, sony xperia series, tablets.
You can check out my accepted answer about rotation of images on this topic:
Camera capture orientation on samsung devices in android
If you also need to save and use that image that you have rotated, saving and using the photo functions additional to my answer I gave above:
savePhoto function:
public void savePhoto(Bitmap bmp) {
imageFileFolder = new File(Environment.getExternalStorageDirectory(),
cc.getDirectoryName());
imageFileFolder.mkdir();
FileOutputStream out = null;
Calendar c = Calendar.getInstance();
String date = fromInt(c.get(Calendar.MONTH))
+ fromInt(c.get(Calendar.DAY_OF_MONTH))
+ fromInt(c.get(Calendar.YEAR))
+ fromInt(c.get(Calendar.HOUR_OF_DAY))
+ fromInt(c.get(Calendar.MINUTE))
+ fromInt(c.get(Calendar.SECOND));
imageFileName = new File(imageFileFolder, date.toString() + ".jpg");
try {
out = new FileOutputStream(imageFileName);
bmp.compress(Bitmap.CompressFormat.JPEG, 70, out);
out.flush();
out.close();
scanPhoto(imageFileName.toString());
out = null;
} catch (Exception e) {
e.printStackTrace();
}
}
scanPhoto function:
public void scanPhoto(final String imageFileName) {
geniusPath = imageFileName;
msConn = new MediaScannerConnection(MyClass.this,
new MediaScannerConnectionClient() {
public void onMediaScannerConnected() {
msConn.scanFile(imageFileName, null);
}
#Override
public void onScanCompleted(String path, Uri uri) {
msConn.disconnect();
}
});
msConn.connect();
}
SavePhotoTask class:
class SavePhotoTask extends AsyncTask<byte[], String, String> {
#Override
protected String doInBackground(byte[]... jpeg) {
File photo = new File(Environment.getExternalStorageDirectory(),
"photo.jpg");
if (photo.exists()) {
photo.delete();
}
try {
FileOutputStream fos = new FileOutputStream(photo.getPath());
fos.write(jpeg[0]);
fos.close();
} catch (java.io.IOException e) {
}
return (null);
}
}
Try below code:-
Uri selectedImageURI = data.getData();
imageFile = new File(getRealPathFromURI(selectedImageURI));
ExifInterface exif = new ExifInterface(imageFile.toString());
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
Bitmap bitmap = Utility.getOrientationFromExif(new Utility().compressImage1(imageFile.toString(),((Activity)context)),orientation);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG , 50 , bos);
Utility.java
public class Utility
{
public Bitmap compressImage1(String imageUri, Activity act)
{
String filePath = getRealPathFromURI(imageUri, act);
BitmapFactory.Options options = new BitmapFactory.Options();
// by setting this field as true, the actual bitmap pixels are not
// loaded in the memory. Just the bounds are loaded. If
// you try the use the bitmap here, you will get null.
options.inJustDecodeBounds = true;
// Bitmap bmp = decodeBitmap(Uri.parse(imageUri), 612, 816, act);
Bitmap bmp = BitmapFactory.decodeFile(filePath, options);
// setting inSampleSize value allows to load a scaled down version of
// the original image
options.inSampleSize = calculateInSampleSize(options, 612, 816);
// inJustDecodeBounds set to false to load the actual bitmap
options.inJustDecodeBounds = false;
// this options allow android to claim the bitmap memory if it runs low
// on memory
options.inPurgeable = true;
options.inInputShareable = true;
options.inTempStorage = new byte[16 * 1024];
// load the bitmap from its path
bmp = BitmapFactory.decodeFile(filePath, options);
return bmp;
}
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight)
{
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth)
{
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and
// keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth)
{
inSampleSize *= 2;
}
}
return inSampleSize;
}
public static Bitmap getOrientationFromExif(Bitmap bitmap, int orientation)
{
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int newWidth = 612;
int newHeight = 816;
// calculate the scale - in this case = 0.4f
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
Matrix matrix = new Matrix();
switch (orientation)
{
case ExifInterface.ORIENTATION_NORMAL:
return bitmap;
case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
// matrix.setScale(-1, 1);
matrix.postScale(scaleWidth, scaleHeight);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
matrix.setRotate(180);
break;
case ExifInterface.ORIENTATION_FLIP_VERTICAL:
matrix.setRotate(180);
// matrix.postScale(-1, 1);
matrix.postScale(scaleWidth, scaleHeight);
break;
case ExifInterface.ORIENTATION_TRANSPOSE:
matrix.setRotate(90);
// matrix.postScale(-1, 1);
matrix.postScale(scaleWidth, scaleHeight);
break;
case ExifInterface.ORIENTATION_ROTATE_90:
matrix.setRotate(90);
break;
case ExifInterface.ORIENTATION_TRANSVERSE:
matrix.setRotate(-90);
// matrix.postScale(-1, 1);
matrix.postScale(scaleWidth, scaleHeight);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
matrix.setRotate(-90);
break;
default:
return bitmap;
}
try
{
Bitmap bmRotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
bitmap.recycle();
return bmRotated;
}
catch (OutOfMemoryError e)
{
e.printStackTrace();
return null;
}
}
}
This function worked for me, try your luck.
public static Bitmap rotateImage(Bitmap bmp, String imageUrl) {
if (bmp != null) {
ExifInterface ei;
int orientation = 0;
try {
ei = new ExifInterface(imageUrl);
orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
} catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
}
int bmpWidth = bmp.getWidth();
int bmpHeight = bmp.getHeight();
Matrix matrix = new Matrix();
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
matrix.postRotate(90);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
matrix.postRotate(180);
break;
default:
break;
// etc.
}
Bitmap resizedBitmap = Bitmap.createBitmap(bmp, 0, 0, bmpWidth,
bmpHeight, matrix, true);
return resizedBitmap;
} else {
return bmp;
}
}