Rotating image using matrix distorts the image when being saved

  • Replies:0
  • OpenNot stickiedUnanswered
  • Forum posts: 10

Sep 21, 2014 3:04:00 AM via Website

I am implementing a custom camera in android. One of the phones that I am using the default display orientation is landscape mode. The preview of the image looks good when taking the picture. Nonetheless, when the immage is rotated and saved the image becomes distorted.

This is the code I am using to rotate the image:

  Display display = ((WindowManager) MyCamera.this.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();

int rotation = display.getRotation();

if (rotation == Surface.ROTATION_0) {
    rotation = 90;

} else if (rotation == Surface.ROTATION_90) {
    rotation = 180;

} else if (rotation == Surface.ROTATION_180) {
    rotation = 270;

} else if (rotation == Surface.ROTATION_270) {
    rotation = 360;
} 

DisplayMetrics metrics = getResources().getDisplayMetrics();
Options options = new BitmapFactory.Options();
options.inDither = false;
options.inScaled = false;
options.inDensity=metrics.densityDpi;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;

bm = BitmapFactory.decodeByteArray(imgBytes, 0, imgBytes.length, options);

Matrix m = new Matrix();
m.postRotate(rotation);                 

Bitmap nbm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), m, true);

file = MyCamera.this.saveBitmap(nbm);

This is the code I'm using to save Bitmap image:

private File saveBitmap(Bitmap image) {

File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);

if (pictureFile == null) {
    Log.d(TAG,"Error creating media file, check storage permissions: ");// e.getMessage());
    return null;
} 

try {



    FileOutputStream fos = new FileOutputStream(pictureFile);
    image.compress(Bitmap.CompressFormat.JPEG, 100, fos);
    fos.close();

} catch (FileNotFoundException e) {
    Log.d(TAG, "File not found: " + e.getMessage());
    finish();
} catch (IOException e) {
    Log.d(TAG, "Error accessing file: " + e.getMessage());
    finish();
}  

return pictureFile;

}

Here are some examples on how the image looks in camera preview mode and how it looks after it is saved on the phones external storage.

image

image

any idea why this is happening?