Java tutorial
//package com.java2s; //License from project: Open Source License import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class Main { public static boolean rotateBitmap(File inFile, File outFile, int angle) throws FileNotFoundException, IOException { // Declare FileInputStream inStream = null; FileOutputStream outStream = null; // Create options BitmapFactory.Options options = new BitmapFactory.Options(); // Create transform matrix Matrix matrix = new Matrix(); matrix.postRotate(angle); // Increment inSampleSize progressively to reduce image resolution and size. If // the program is properly managing memory, and you don't have other large images // loaded in memory, this loop will generally not need to go through more than 3 // iterations. To be safe though, we stop looping after a certain amount of tries // to avoid infinite loops for (options.inSampleSize = 1; options.inSampleSize <= 32; options.inSampleSize++) { try { // Load the bitmap from file inStream = new FileInputStream(inFile); Bitmap originalBitmap = BitmapFactory.decodeStream(inStream, null, options); // Rotate the bitmap Bitmap rotatedBitmap = Bitmap.createBitmap(originalBitmap, 0, 0, originalBitmap.getWidth(), originalBitmap.getHeight(), matrix, true); // Save the rotated bitmap outStream = new FileOutputStream(outFile); rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream); outStream.close(); // Recycle the bitmaps to immediately free memory originalBitmap.recycle(); originalBitmap = null; rotatedBitmap.recycle(); rotatedBitmap = null; // Return return true; } catch (OutOfMemoryError e) { // If an OutOfMemoryError occurred, we continue with for loop and next inSampleSize value } finally { // Clean-up if we failed on save if (outStream != null) { try { outStream.close(); } catch (IOException e) { } } } } // Failed return false; } }