Search code examples
androidimagefileiocamera

Android Rotate Picture before saving


I just finished my camera activity and it's wonderfully saving the data. What I do after the picture is taken:

protected void savePictureData() {
    try {
        FileOutputStream fs = new FileOutputStream(this.photo);
        fs.write(this.lastCamData);
        fs.close(); //okay, wonderful! file is just written to the sdcard

        //---------------------
        //---------------------
        //TODO in here: dont save just the file but ROTATE the image and then save it!
        //---------------------
        //---------------------


        Intent data = new Intent(); //just a simple intent returning some data...
        data.putExtra("picture_name", this.fname);
        data.putExtra("byte_data", this.lastCamData);
        this.setResult(SAVED_TOOK_PICTURE, data);
        this.finish(); 
    } catch (IOException e) {
        e.printStackTrace();
        this.IOError();
    }

}

What I want to is already as comment given in the code above. I dont want the image just to be saved to file but to be rotated and then saved! Thanks!

//EDIT: What I am currently up to (Works but still runs into memory issues with large images)

byte[] pictureBytes;
Bitmap thePicture = BitmapFactory.decodeByteArray(this.lastCamData, 0, this.lastCamData.length);
Matrix m = new Matrix();
m.postRotate(90);
thePicture = Bitmap.createBitmap(thePicture, 0, 0, thePicture.getWidth(), thePicture.getHeight(), m, true);

ByteArrayOutputStream bos = new ByteArrayOutputStream();
thePicture.compress(CompressFormat.JPEG, 100, bos);
pictureBytes = bos.toByteArray();

FileOutputStream fs = new FileOutputStream(this.photo);
fs.write(pictureBytes);
fs.close();
Intent data = new Intent();
data.putExtra("picture_name", this.fname);
data.putExtra("byte_data", pictureBytes);
this.setResult(SAVED_TOOK_PICTURE, data);
this.finish();

Solution

  • Before you create your FileOutputStream you can create a new Bitmap from the original that has been transformed using a Matrix. To do that you would use this method:

    createBitmap(Bitmap source, int x, int y, int width, int height, Matrix m, boolean filter)
    

    Where the m defines a matrix that will transpose your original bitmap.

    For an example on how to do this look at this question: Android: How to rotate a bitmap on a center point