Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/*
 * Copyright (C) 2010 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 android.graphics.Bitmap;

import android.graphics.Matrix;

import android.util.Log;

public class Main {
    public static Bitmap resizeBitmap(Bitmap input, int destWidth, int destHeight, int rotation)
            throws OutOfMemoryError {
        int dstWidth = destWidth;
        int dstHeight = destHeight;
        int srcWidth = input.getWidth();
        int srcHeight = input.getHeight();

        if ((rotation == 90) || (rotation == 270)) {
            dstWidth = destHeight;
            dstHeight = destWidth;
        }

        boolean needsResize = false;

        if ((srcWidth > dstWidth) || (srcHeight > dstHeight)) {
            needsResize = true;

            float ratio1 = (float) srcWidth / dstWidth;
            float ratio2 = (float) srcHeight / dstHeight;
            Log.v("dsd", "ratio1:" + ratio1 + " ratio2:" + ratio2);

            if (ratio1 > ratio2) {
                float p = (float) dstWidth / srcWidth;
                dstHeight = (int) (srcHeight * p);
            } else {
                float p = (float) dstHeight / srcHeight;
                dstWidth = (int) (srcWidth * p);
            }
        } else {
            dstWidth = srcWidth;
            dstHeight = srcHeight;
        }

        Log.v("dsd", "dstWidth:" + dstWidth + " dstHeight:" + dstHeight + " srcWidth:" + srcWidth + " srcHeight:"
                + srcHeight);
        if ((needsResize) || (rotation != 0)) {
            Bitmap output = null;
            if (rotation == 0) {
                output = Bitmap.createScaledBitmap(input, dstWidth, dstHeight, true);
            } else {
                Matrix matrix = new Matrix();
                matrix.postScale((float) dstWidth / srcWidth, (float) dstHeight / srcHeight);
                matrix.postRotate(rotation);
                output = Bitmap.createBitmap(input, 0, 0, srcWidth, srcHeight, matrix, true);
            }
            return output;
        }
        return input;
    }
}