I'm doing an app which takes a photo with the camera and then rotates it and scales it. I need to rotate the image because the camera returns a wrong rotated image and I need to scale it to reduce its size. I first save in a temp directory the original image returned by camera, then I read it and make modifications, saving the new image to a new file. I tried using matrix to rotate and scale the picture, but it loses quality. Then I tried to scale it first with Bitmap.createScaledBitmap and then rotate it with matrix, but the result is even uglier than the one using only matrix. Then I tried to rotate it first and then resize it using always Bitmap.createScaledBitmap. The image doesn't lose quality, but it's stretched as I scaled it after rotating it and width and height are inverted. Tried also to invert height and width according to the rotation made, but it loses quality again. This is the last code I've written:
in= new FileInputStream(tempDir+"/"+photo1_path);
out = new FileOutputStream(file+"/picture.png");
Bitmap src = BitmapFactory.decodeStream(in);
int iwidth = src.getWidth();
int iheight = src.getHeight();
int newWidth = 0;
int newHeight = 0;
newWidth = 800;
newHeight = 600;
// calculate the scale - in this case = 0.4f
float scaleWidth = ((float) newWidth) / iwidth;
float scaleHeight = ((float) newHeight) / iheight;
// createa matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
//matrix.postScale(scaleWidth, scaleHeight);
int orientation = getOrientation(MyActivity.this,Uri.parse(tempDir+"/"+photo1_path));
switch(orientation) {
case 3:
orientation = 180;
break;
case 6:
orientation = 90;
break;
case 8:
orientation = 270;
break;
}
int rotate = 0;
switch(orientation) {
case 90:
rotate=90;
break;
case 180:
rotate=180;
break;
case 270:
rotate=270;
break;
}
// rotate the Bitmap
matrix.postRotate(rotate);
src =Bitmap.createScaledBitmap(src , newWidth, newHeight, false);
// recreate the new Bitmap
Bitmap new_bit = Bitmap.createBitmap(src, 0, 0,
src.getWidth(), src.getHeight(), matrix, true);
new_bit.compress(Bitmap.CompressFormat.PNG, 100, out);
Any advice?
EDIT: If I only rotate or only scale the image, it doesn't lose quality. It's when I do both that the image loses quality. Also, if I put the image in an ImageView after resizing it and scaling it, it doesn't lose quality, it's just when I save it to file that loses quality.