crop Bitmap by ratio - Android Graphics

Android examples for Graphics:Bitmap Crop

Description

crop Bitmap by ratio

Demo Code

/*//from   w  w w .  j a  v  a2 s. c om
 Copyright (C) 2015 R?mi Jouannet <remijouannet@gmail.com>
 This file is part of get10.
 get10 is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

public class Main{
    private final static String TAG = BitmapHelper.class.getSimpleName();
    public static Bitmap cropBitmap(Bitmap bitmap, float ratio) {
        float bitmapRatio = (float) bitmap.getWidth()
                / (float) bitmap.getHeight();
        if (bitmapRatio != ratio) {
            float finalHeight = bitmap.getWidth() / ratio;
            return cropBitmap(bitmap, bitmap.getWidth(), (int) finalHeight);
        } else {
            return bitmap;
        }
    }
    public static Bitmap cropBitmap(Bitmap bitmap, int width, int height) {
        try {
            Bitmap newBitmap = Bitmap.createBitmap(bitmap, 0, 0, width,
                    height);
            return newBitmap;
        } catch (Exception ex) {
            ex.printStackTrace();
            return bitmap;
        }
    }
    public static Bitmap cropBitmap(Bitmap bitmap, int x, int y, int width,
            int height) {
        try {
            Bitmap newBitmap = Bitmap.createBitmap(bitmap, x, y, width,
                    height);
            return newBitmap;
        } catch (Exception ex) {
            Log.d(TAG, ex.getMessage());
            return bitmap;
        }
    }
}

Related Tutorials