Подтвердить что ты не робот

Уменьшите размер Bitmap до определенного пикселя в Android

Я хотел бы уменьшить размер моего растрового изображения до 640 пикселей. Например, у меня есть растровое изображение размером 1200 x 1200 px. Как я могу уменьшить его до 640px.

4b9b3361

Ответ 1

Если вы передаете растровые изображения width и height, то используйте:

public Bitmap getResizedBitmap(Bitmap image, int bitmapWidth, int bitmapHeight) {
    return Bitmap.createScaledBitmap(image, bitmapWidth, bitmapHeight, true);
}

Если вы хотите сохранить соотношение растрового изображения одинаковым, но уменьшите его до максимальной длины стороны, используйте:

public Bitmap getResizedBitmap(Bitmap image, int maxSize) {
        int width = image.getWidth();
        int height = image.getHeight();

        float bitmapRatio = (float) width / (float) height;
        if (bitmapRatio > 1) {
            width = maxSize;
            height = (int) (width / bitmapRatio);
        } else {
            height = maxSize;
            width = (int) (height * bitmapRatio);
        }

        return Bitmap.createScaledBitmap(image, width, height, true);
}

Ответ 2

Используйте этот метод

 /** getResizedBitmap method is used to Resized the Image according to custom width and height 
  * @param image
  * @param newHeight (new desired height)
  * @param newWidth (new desired Width)
  * @return image (new resized image)
  * */
public static Bitmap getResizedBitmap(Bitmap image, int newHeight, int newWidth) {
    int width = image.getWidth();
    int height = image.getHeight();
    float scaleWidth = ((float) newWidth) / width;
    float scaleHeight = ((float) newHeight) / height;
    // create a matrix for the manipulation
    Matrix matrix = new Matrix();
    // resize the bit map
    matrix.postScale(scaleWidth, scaleHeight);
    // recreate the new Bitmap
    Bitmap resizedBitmap = Bitmap.createBitmap(image, 0, 0, width, height,
            matrix, false);
    return resizedBitmap;
}

Ответ 3

или вы можете сделать это следующим образом:

Bitmap.createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, boolean filter);

Passing filter = false приведет к блочному пикселируемому изображению.

Passing filter = true даст вам более гладкие ребра.