Android Bitmap Compress compressWithWidth(Bitmap bitmap, int width)

Here you can find the source of compressWithWidth(Bitmap bitmap, int width)

Description

compress With Width

Declaration

public static Bitmap compressWithWidth(Bitmap bitmap, int width) 

Method Source Code

//package com.java2s;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import android.graphics.Matrix;

public class Main {

    public static Bitmap compressWithWidth(String filePath, int width) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);

        int bmpWidth = options.outWidth;
        int bmpHeight = options.outHeight;

        options.inJustDecodeBounds = false;
        bitmap = BitmapFactory.decodeFile(filePath, options);

        float scaleWidth = bmpWidth;
        float scaleHeight = bmpHeight;

        if (bmpWidth > width) {
            scaleWidth = width / scaleWidth;
            scaleHeight = scaleWidth;/*from ww  w.  ja  v a 2s  .  c o  m*/
        } else {
            scaleWidth = 1;
            scaleHeight = 1;
        }

        Matrix matrix = new Matrix();

        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap resizeBitmap = Bitmap.createBitmap(bitmap, 0, 0, bmpWidth,
                bmpHeight, matrix, false);

        if (bitmap != resizeBitmap) {
            bitmap.recycle();
        }
        return resizeBitmap;
    }

    public static Bitmap compressWithWidth(Bitmap bitmap, int width) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;

        int bmpWidth = options.outWidth;
        int bmpHeight = options.outHeight;

        options.inJustDecodeBounds = false;

        float scaleWidth = bmpWidth;
        float scaleHeight = bmpHeight;

        if (bmpWidth > width) {
            scaleWidth = width / scaleWidth;
            scaleHeight = scaleWidth;
        } else {
            scaleWidth = 1;
            scaleHeight = 1;
        }

        Matrix matrix = new Matrix();

        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap resizeBitmap = Bitmap.createBitmap(bitmap, 0, 0, bmpWidth,
                bmpHeight, matrix, false);

        if (bitmap != resizeBitmap) {
            bitmap.recycle();
        }
        return resizeBitmap;
    }
}

Related

  1. compressBitmapToFile(Bitmap originalBitmap, String path, int quality)
  2. compressToBytes(Bitmap bitmap)
  3. compressToBytes(Bitmap bitmap, int quality)
  4. flattenBitmap(Bitmap bitmap)
  5. smallPic(String oldPath, String newPath, int size)
  6. compressWithWidth(String filePath, int width)
  7. compressBitmap(Bitmap bitmap)
  8. compressToBytes(Bitmap bitmap, int quality)
  9. compress(String srcPath, String dstPath, int maxWidth, int maxHeight, long maxSize, CompressFormat format)