Example usage for android.graphics BitmapFactory decodeFile

List of usage examples for android.graphics BitmapFactory decodeFile

Introduction

In this page you can find the example usage for android.graphics BitmapFactory decodeFile.

Prototype

public static Bitmap decodeFile(String pathName, Options opts) 

Source Link

Document

Decode a file path into a bitmap.

Usage

From source file:Main.java

/**
 * Load the image at {@code imagePath} as a {@link Bitmap}, scaling it to
 * the specified size and preserving the aspect ratio.
 * @param imagePath Path of the image to load.
 * @param width Required width of the resulting {@link Bitmap}.
 * @param height Required height of the resulting {@link Bitmap}.
 * @param fill {@code true} to fill the empty space with transparent color.
 * @param crop {@code true} to crop the image, {@code false} to resize without cutting the image.
 * @return {@link Bitmap} representing the image at {@code imagePath}.
 *//*ww w. ja  v  a  2  s .c  om*/
public static Bitmap loadResizedBitmap(String imagePath, int width, int height, boolean fill, boolean crop) {
    Bitmap retVal;

    BitmapFactory.Options opts = new BitmapFactory.Options();
    opts.inSampleSize = getScale(imagePath, width, height);
    opts.inJustDecodeBounds = false;

    Bitmap image = BitmapFactory.decodeFile(imagePath, opts);

    if (image == null) {
        if (imagePath != null) {
            Log.w("Helper", "Cannot decode " + imagePath);
        } else {
            Log.w("Helper", "Path is null: Cannot decode");
        }
        return null;
    }

    if (image.getWidth() != width || image.getHeight() != height) {
        //Image need to be resized.
        int scaledWidth = (image.getWidth() * height) / image.getHeight();
        int scaledHeight;
        if ((crop && scaledWidth > width) || (!crop && scaledWidth < width)) {
            scaledHeight = height;
        } else {
            scaledWidth = width;
            scaledHeight = (image.getHeight() * width) / image.getWidth();
        }

        Rect src = new Rect(0, 0, image.getWidth(), image.getHeight());
        Rect dst = new Rect(0, 0, scaledWidth, scaledHeight);

        if (fill) {
            retVal = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            dst.offset((width - scaledWidth) / 2, (height - scaledHeight) / 2);
        } else {
            retVal = Bitmap.createBitmap(scaledWidth, scaledHeight, Bitmap.Config.ARGB_8888);
        }
        retVal.eraseColor(Color.TRANSPARENT);

        synchronized (canvas) {
            if (antiAliasPaint == null) {
                antiAliasPaint = new Paint();
                antiAliasPaint.setAntiAlias(true);
                antiAliasPaint.setFilterBitmap(true);
                antiAliasPaint.setDither(true);
            }
            canvas.setBitmap(retVal);
            canvas.drawBitmap(image, src, dst, antiAliasPaint);
        }

        image.recycle();
    } else {
        //No need to scale.
        retVal = image;
    }

    return retVal;
}

From source file:Main.java

/**
 * Decodes a bitmap from a file containing it minimizing the memory use, known that the bitmap
 * will be drawn in a surface of reqWidth x reqHeight
 * /*w w  w .j  ava2 s. c  o m*/
 * @param srcPath       Absolute path to the file containing the image.
 * @param reqWidth      Width of the surface where the Bitmap will be drawn on, in pixels.
 * @param reqHeight     Height of the surface where the Bitmap will be drawn on, in pixels.
 * @return
 */
public static Bitmap decodeSampledBitmapFromFile(String srcPath, int reqWidth, int reqHeight) {

    // set desired options that will affect the size of the bitmap
    final Options options = new Options();
    options.inScaled = true;
    options.inPurgeable = true;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1) {
        options.inPreferQualityOverSpeed = false;
    }
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
        options.inMutable = false;
    }

    // make a false load of the bitmap to get its dimensions
    options.inJustDecodeBounds = true;

    BitmapFactory.decodeFile(srcPath, options);

    // calculate factor to subsample the bitmap
    options.inSampleSize = calculateSampleFactor(options, reqWidth, reqHeight);

    // decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeFile(srcPath, options);

}

From source file:Main.java

/**
 * Decodes an image File to Bitmap resizing the image to fit the <code>requestedWidth</code> and <code>requestedHeight</code> dimensions.
 * @param file the image file reference/*from   w w  w. j  a va 2s  . c  o  m*/
 * @param requestedWidth the final image width will be close to the requestedWidth (value is in pixels)
 * @param requestedHeight the final image height will be close to the requestedHeight (value is in pixels)
 * @return the resized Bitmap
 */
public static Bitmap decodeSampledBitmapFromFile(File file, int requestedWidth, int requestedHeight) {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;

    BitmapFactory.decodeFile(file.getPath(), options);

    int inSampleSize = calculateSampleSize(options, requestedWidth, requestedHeight);

    return decodeSampledBitmapFromFile(file, inSampleSize);
}

From source file:Main.java

public static Bitmap decodeSampledBitmapFromFile(String filePath, int reqWidth, int reqHeight) {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;/*from w  w  w.  j a  v a  2 s.com*/
    BitmapFactory.decodeFile(filePath, options);

    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
    options.inJustDecodeBounds = false;

    return BitmapFactory.decodeFile(filePath, options);
}

From source file:Main.java

/****************************************************************************************************************
 * Get the image bitmap that resizing to maximum size of limit.
 * Parameter :/*  w  ww .  j av a 2 s  .co m*/
 *  - context : Context 
 *  - uri : Image URI
 *  - bContentStreamImage : Gallery contents stream file(true)/file path(false)
 *  - nMaxResizedWidth : The maximum allowable width of resizing image.
 *  - nMaxResizedHeight : The maximum allowable height of resizing image.
 * Return :
 *  - Resizing bitmap
 */
public static Bitmap getSafeResizingBitmap(String strImagePath, int nMaxResizedWidth, int nMaxResizedHeight,
        boolean checkOrientation) {
    //==========================================
    // Bitmap Option
    //==========================================
    BitmapFactory.Options options = getBitmapSize(strImagePath);
    if (options == null)
        return null;

    //==========================================
    // Bitmap Scaling
    //==========================================
    int nSampleSize;
    int degree = 0;
    if (checkOrientation) {
        degree = getExifDegree(strImagePath);
    }

    if (degree == 90 || degree == 270) {
        nSampleSize = getSafeResizingSampleSize(options.outHeight, options.outWidth, nMaxResizedWidth,
                nMaxResizedHeight);
    } else {
        nSampleSize = getSafeResizingSampleSize(options.outWidth, options.outHeight, nMaxResizedWidth,
                nMaxResizedHeight);
    }

    //==========================================
    // Load the bitmap including actually data.
    //==========================================
    options.inJustDecodeBounds = false;
    options.inSampleSize = nSampleSize;
    options.inDither = false;
    options.inPreferredConfig = Config.ARGB_8888;
    options.inPurgeable = true;

    Bitmap photo = BitmapFactory.decodeFile(strImagePath, options);
    if (checkOrientation && (degree == 90 || degree == 270)) {
        return getRotatedBitmap(photo, degree);
    }
    return photo;
}

From source file:Main.java

/**
 * //from ww w  . j  ava  2 s. co m
 * @param filePath
 * @param targetWidth
 * @param targetHeight
 * @param recycle
 * @return
 */
public static Bitmap resizeAndCropCenter(String filePath, int targetWidth, int targetHeight, boolean recycle) {
    //get sampleBitmap
    Options opts = new Options();
    opts.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath, opts);

    int scaleWidth = opts.outWidth / targetWidth;
    int scaleHeight = opts.outHeight / targetHeight;
    int scale = scaleWidth < scaleHeight ? scaleWidth : scaleHeight;
    if (scale < 1) {
        scale = 1;
    }
    opts.inJustDecodeBounds = false;
    opts.inSampleSize = scale;
    Bitmap sampleBitmap = BitmapFactory.decodeFile(filePath, opts);

    if (opts.outWidth == -1 || opts.outHeight == -1) {
        throw new IllegalArgumentException();
    }
    //get scalebitmap
    float fScaleWidth = targetWidth / ((float) opts.outWidth);
    float fScaleHeight = targetHeight / ((float) opts.outHeight);
    float fScale = fScaleWidth > fScaleHeight ? fScaleWidth : fScaleHeight;
    if (fScale > 1)
        fScale = 1;
    Matrix matrix = new Matrix();
    matrix.postScale(fScale, fScale);
    Bitmap scaleBitmap = Bitmap.createBitmap(sampleBitmap, 0, 0, opts.outWidth, opts.outHeight, matrix, true);

    //get targetBitmap
    int bitmapX = (scaleBitmap.getWidth() - targetWidth) / 2;
    bitmapX = bitmapX > 0 ? bitmapX : 0;
    int bitmapY = (scaleBitmap.getHeight() - targetHeight) / 2;
    bitmapY = bitmapY > 0 ? bitmapY : 0;
    targetWidth = targetWidth < (scaleBitmap.getWidth()) ? targetWidth : (scaleBitmap.getWidth());
    targetHeight = targetHeight < (scaleBitmap.getHeight()) ? targetHeight : (scaleBitmap.getHeight());
    Bitmap targetBitmap = Bitmap.createBitmap(scaleBitmap, bitmapX, bitmapY, targetWidth, targetHeight);

    if (recycle)
        sampleBitmap.recycle();
    return targetBitmap;
}

From source file:Main.java

/**
 * Allows decoding of a bitmap with a specified height and width.
 * //from  ww w . j a v  a2 s.  c  om
 * Modified from the Android developer tutorial. Original source can be
 * found at {@link http
 * ://developer.android.com/training/displaying-bitmaps/load-bitmap.html}
 * 
 * @param filename
 *            The filename of the file to be decoded.
 * @param reqWidth
 *            The preferred width of the output bitmap.
 * @param reqHeight
 *            The preferred height of the output bitmap.
 * @return the decoded bitmap, or null
 */
public static Bitmap decodeSampledBitmapFromFile(String filename, float reqWidth, float reqHeight) {
    Log.v(TAG, "Recieved " + filename + " with (w,h): (" + reqWidth + ", " + reqHeight + ").");
    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filename, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    Bitmap decodedBitmap = BitmapFactory.decodeFile(filename, options);
    Log.v(TAG, "The Bitmap is " + decodedBitmap.toString());
    return decodedBitmap;
}

From source file:Main.java

public static Bitmap decodeSampledBitmapFromPath(String localpath, long allowedBmpMaxMemorySize) {
    try {//from  w ww  .j a v  a2 s .c  om
        final Options options = new Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(localpath, options);
        options.inSampleSize = calculateInSampleSize(options, allowedBmpMaxMemorySize);
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(localpath, options);
    } catch (Throwable err) {
        err.printStackTrace();

    }
    return null;
}

From source file:Main.java

/****************************************************************************************************************
 * Get the image bitmap that resizing to maximum size of limit.
 * Parameter :/*  w ww.  j a v  a2s .c  om*/
 *  - context : Context 
 *  - uri : Image URI
 *  - bContentStreamImage : Gallery contents stream file(true)/file path(false)
 *  - nMaxResizedWidth : The maximum allowable width of resizing image.
 *  - nMaxResizedHeight : The maximum allowable height of resizing image.
 * Return :
 *  - Resizing bitmap
 */
public static Bitmap getSafeResizingBitmap(String strImagePath, int nMaxResizedWidth, int nMaxResizedHeight,
        boolean checkOrientation) {
    //==========================================
    // Bitmap Option
    //==========================================
    BitmapFactory.Options options = getBitmapSize(strImagePath);
    if (options == null)
        return null;

    //==========================================
    // Bitmap Scaling
    //==========================================
    int nSampleSize;
    int degree = 0;
    if (checkOrientation) {
        degree = getExifDegree(strImagePath);
    }

    if (degree == 90 || degree == 270) {
        nSampleSize = getSafeResizingSampleSize(options.outHeight, options.outWidth, nMaxResizedWidth,
                nMaxResizedHeight);
    } else {
        nSampleSize = getSafeResizingSampleSize(options.outWidth, options.outHeight, nMaxResizedWidth,
                nMaxResizedHeight);
    }

    //==========================================
    // Load the bitmap including actually data.
    //==========================================
    options.inJustDecodeBounds = false;
    options.inSampleSize = nSampleSize;
    options.inDither = false;
    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
    options.inPurgeable = true;

    Bitmap photo = BitmapFactory.decodeFile(strImagePath, options);
    if (checkOrientation && (degree == 90 || degree == 270)) {
        return getRotatedBitmap(photo, degree);
    }
    return photo;
}

From source file:Main.java

public static BitmapFactory.Options getBitmapOptions(String pathName) {
    BitmapFactory.Options opts = new BitmapFactory.Options();
    opts.inJustDecodeBounds = true;//from  w ww . jav a  2 s .c om
    BitmapFactory.decodeFile(pathName, opts);
    return opts;
}