Android rotate image

In an application, there might be a requirement to rotate an image. In this Android tip, I am going to show you how to achieve this goal.
One method to rotate the image in Android uses createBitmap (Bitmap source, int x, int y, int width, int height, Matrix matrix, boolean filter) method of the Bitmap class. The first parameter is an instance of Bitmap class for the source image. You will use decodeFile(), decodeByteArray(), decodeResource(), or decodeStream() of the BitmapFactory class to create Bitmap object for the source image. The second and third parameters are x and coordinates of the first pixel in the source image. The fourth and fifth parameters are width and height of the result image. The matrix parameter is to be applied to the pixels to transform the source image. With an instance of Matrix class, you can specify an angle to rotate the image. The filter parameter specifies whether the source image should be filtered.
Now to have an example application on rotating an image, you create a new Android project. Then in the activity_main.xml file, you add an ImageView and a Button as shown below.

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android=""
   android:layout_height="match_parent" >

     android:text="Rotate" />


Here is the code written in The MainActivity class to rotate the image when the user clicks the Rotate button.

public class MainActivity extends Activity{
    Button buttonClick;
    ImageView img;
    Bitmap source;
    float angle=0;
    protected void onCreate(Bundle savedInstanceState) {
       img= (ImageView) findViewById(;
       // Create Bitmap object for the source image
       buttonClick = (Button) findViewById(;
       buttonClick.setOnClickListener(new OnClickListener(){
     public void onClick(View view){
     Bitmap rotatedImage=rotateImage(source,angle);
    public static Bitmap rotateImage(Bitmap sourceImage, float angle)
        Matrix matrix = new Matrix();
        return Bitmap.createBitmap(sourceImage, 0, 0, sourceImage.getWidth(), sourceImage.getHeight(), matrix, true);



Posted by: Dara | post date: 01-21-2015 | Subject: Android Apps Development

write programming tip

This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.