Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/*
 * Copyright (C) 2015 Bilibili <jungly.ik@gmail.com>
 *
 * 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.BitmapFactory;

public class Main {
    public static Bitmap decodeFile(String path, float width, float height) {
        int inSampleSize = getInSampleSize(path, width, height);
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        newOpts.inSampleSize = inSampleSize;
        newOpts.inJustDecodeBounds = false;
        newOpts.inPreferredConfig = Bitmap.Config.RGB_565;
        return BitmapFactory.decodeFile(path, newOpts);
    }

    private static int getInSampleSize(String path, float width, float height) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        newOpts.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, newOpts);
        int outWidth = newOpts.outWidth;
        int outHeight = newOpts.outHeight;
        return (int) getScale(width, height, outWidth, outHeight);
    }

    public static double getScale(float targetWidth, float targetHeight, float bmpWidth, float bmpHeight) {
        double be;
        if (bmpWidth >= bmpHeight) {
            float widthScale = bmpWidth / targetHeight;
            float heightScale = bmpHeight / targetWidth;
            if (widthScale >= heightScale) {
                be = Math.rint(widthScale);
            } else {
                be = Math.rint(heightScale);
            }
        } else {
            float widthScale = bmpWidth / targetWidth;
            float heightScale = bmpHeight / targetHeight;
            if (widthScale >= heightScale) {
                be = widthScale;
            } else {
                be = heightScale;
            }
        }
        if (be <= 0) {
            return 1.0;
        }

        return be;
    }
}