Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.awt.image.BufferedImage;

public class Main {
    /**
     * Rotates given image by given degrees which should be a multiple of 90
     * @param source image to be rotated
     * @param degrees the angle by which to rotate, should be a multiple of 90
     * @return the rotated image
     */
    public static BufferedImage rotateByRightAngle(BufferedImage source, int degrees) {
        assert degrees % 90 == 0;
        degrees = degrees % 360;

        int w = source.getWidth();
        int h = source.getHeight();
        int w1, h1;
        switch (degrees) {
        case 90:
        case 270:
            w1 = h;
            h1 = w;
            break;
        default:
            w1 = w;
            h1 = h;
        }
        BufferedImage rotated = new BufferedImage(w1, h1, source.getType());

        for (int x = 0; x < w; x++) {
            for (int y = 0; y < h; y++) {
                int v = source.getRGB(x, y);
                int x1, y1;
                switch (degrees) {
                case 90:
                    x1 = h - y - 1;
                    y1 = x;
                    break;
                case 180:
                    x1 = w - x - 1;
                    y1 = h - y - 1;
                    break;
                case 270:
                    x1 = y;
                    y1 = w - x - 1;
                    break;
                default:
                    x1 = x;
                    y1 = y;
                    break;
                }

                rotated.setRGB(x1, y1, v);
            }
        }

        return rotated;
    }
}