rotate image and return bitmap to store it in a proper rotated format - Android Graphics

Android examples for Graphics:Bitmap Rotate

Description

rotate image and return bitmap to store it in a proper rotated format

Demo Code


//package com.java2s;

import android.content.Context;

import android.content.res.Configuration;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;

public class Main {
    /**//from  w  w  w. jav  a  2  s  .  co m
     * 
     * rotate image and return bitmap to store it in a proper rotated format
     * @param data byte array to convert in bitmap
     * @return properly rotated bitmap object or null 
     */
    public static Bitmap rotateImage(byte[] data, Context context) {
        if (data != null) {
            int screenWidth = context.getResources().getDisplayMetrics().widthPixels;
            int screenHeight = context.getResources().getDisplayMetrics().heightPixels;
            Bitmap bm = BitmapFactory.decodeByteArray(data, 0,
                    (data != null) ? data.length : 0);

            if (context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
                // Notice that width and height are reversed
                Bitmap scaled = Bitmap.createScaledBitmap(bm, screenHeight,
                        screenWidth, true);
                int w = scaled.getWidth();
                int h = scaled.getHeight();
                // Setting post rotate to 90
                Matrix mtx = new Matrix();
                mtx.postRotate(90);
                // Rotating Bitmap
                bm = Bitmap.createBitmap(scaled, 0, 0, w, h, mtx, true);
            } else {// LANDSCAPE MODE
                    //No need to reverse width and height
                Bitmap scaled = Bitmap.createScaledBitmap(bm, screenWidth,
                        screenHeight, true);
                bm = scaled;
            }
            return bm;
        }
        return null;
    }
}

Related Tutorials