Android Bitmap Compress compressWithWidth(String filePath, int width)

Here you can find the source of compressWithWidth(String filePath, int width)

Description

compress With Width

Declaration

public static Bitmap compressWithWidth(String filePath, 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   w w  w  . ja v  a  2s.com
        } 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. compressToBytes(Bitmap bitmap)
  2. compressToBytes(Bitmap bitmap, int quality)
  3. flattenBitmap(Bitmap bitmap)
  4. smallPic(String oldPath, String newPath, int size)
  5. compressWithWidth(Bitmap bitmap, int width)
  6. compressBitmap(Bitmap bitmap)
  7. compressToBytes(Bitmap bitmap, int quality)
  8. compress(String srcPath, String dstPath, int maxWidth, int maxHeight, long maxSize, CompressFormat format)
  9. compress(byte[] data, String dstPath, int maxWidth, int maxHeight, long maxSize, CompressFormat format)