Example usage for android.graphics Bitmap createScaledBitmap

List of usage examples for android.graphics Bitmap createScaledBitmap

Introduction

In this page you can find the example usage for android.graphics Bitmap createScaledBitmap.

Prototype

public static Bitmap createScaledBitmap(@NonNull Bitmap src, int dstWidth, int dstHeight, boolean filter) 

Source Link

Document

Creates a new bitmap, scaled from an existing bitmap, when possible.

Usage

From source file:Main.java

public static Bitmap resizeBitmapToImageView(String path) {
    Bitmap resizedBitmap = null;/*from ww w.ja v  a2s .c  o  m*/
    try {
        int inWidth;
        int inHeight;
        int dstWidth = 1000;
        int dstHeight = 1000;

        InputStream in = new FileInputStream(path);

        // decode image size (decode metadata only, not the whole image)
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(in, null, options);
        in.close();

        // save width and height
        inWidth = options.outWidth;
        inHeight = options.outHeight;

        // decode full image pre-resized
        in = new FileInputStream(path);
        options = new BitmapFactory.Options();
        // calc rought re-size (this is no exact resize)

        options.inSampleSize = Math.max(inWidth / dstWidth, inHeight / dstHeight);
        // decode full image
        Bitmap roughBitmap = BitmapFactory.decodeStream(in, null, options);

        // calc exact destination size
        Matrix m = new Matrix();
        RectF inRect = new RectF(0, 0, roughBitmap.getWidth(), roughBitmap.getHeight());
        RectF outRect = new RectF(0, 0, dstWidth, dstHeight);
        m.setRectToRect(inRect, outRect, Matrix.ScaleToFit.CENTER);
        float[] values = new float[9];
        m.getValues(values);

        // resize bitmap
        resizedBitmap = Bitmap.createScaledBitmap(roughBitmap, (int) (roughBitmap.getWidth() * values[0]),
                (int) (roughBitmap.getHeight() * values[4]), true);

        // save image
        //            try {
        //                FileOutputStream out = new FileOutputStream(path);
        //                resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);
        //            } catch (Exception e) {
        ////                Log.e("Image", e.getMessage(), e);
        //            }
    } catch (IOException e) {
        //            Log.e("Image", e.getMessage(), e);
    }
    return resizedBitmap;
}

From source file:Main.java

private static void saveSmallerImage(String pathOfInputImage, int dstWidth, int dstHeight) {
    try {//from w ww  .  ja  v  a  2  s  .c  om
        int inWidth = 0;
        int inHeight = 0;

        InputStream in = new FileInputStream(pathOfInputImage);

        // decode image size (decode metadata only, not the whole image)
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(in, null, options);
        in.close();
        in = null;

        // save width and height
        inWidth = options.outWidth;
        inHeight = options.outHeight;

        // decode full image pre-resized
        in = new FileInputStream(pathOfInputImage);
        options = new BitmapFactory.Options();
        // calc rought re-size (this is no exact resize)
        options.inSampleSize = Math.max(inWidth / dstWidth, inHeight / dstHeight);
        // decode full image
        Bitmap roughBitmap = BitmapFactory.decodeStream(in, null, options);

        // calc exact destination size
        Matrix m = new Matrix();
        RectF inRect = new RectF(0, 0, roughBitmap.getWidth(), roughBitmap.getHeight());
        RectF outRect = new RectF(0, 0, dstWidth, dstHeight);
        m.setRectToRect(inRect, outRect, Matrix.ScaleToFit.CENTER);
        float[] values = new float[9];
        m.getValues(values);

        // resize bitmap
        Bitmap resizedBitmap = Bitmap.createScaledBitmap(roughBitmap,
                (int) (roughBitmap.getWidth() * values[0]), (int) (roughBitmap.getHeight() * values[4]), true);

        // save image
        try {
            FileOutputStream out = new FileOutputStream(pathOfInputImage);
            resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);
        } catch (Exception e) {
            Log.e("Image", e.getMessage(), e);
        }
    } catch (IOException e) {
        Log.e("Image", e.getMessage(), e);
    } catch (Exception e) {
        Log.e("Image", e.getMessage());
    }
}

From source file:Main.java

/**
 * Stack Blur v1.0 from/*from w  w w.j a  v a  2  s. com*/
 * http://www.quasimondo.com/StackBlurForCanvas/StackBlurDemo.html
 * Java Author: Mario Klingemann <mario at quasimondo.com>
 * http://incubator.quasimondo.com
 * <p/>
 * created Feburary 29, 2004
 * Android port : Yahel Bouaziz <yahel at kayenko.com>
 * http://www.kayenko.com
 * ported april 5th, 2012
 * <p/>
 * This is a compromise between Gaussian Blur and Box blur
 * It creates much better looking blurs than Box Blur, but is
 * 7x faster than my Gaussian Blur implementation.
 * <p/>
 * I called it Stack Blur because this describes best how this
 * filter works internally: it creates a kind of moving stack
 * of colors whilst scanning through the image. Thereby it
 * just has to add one new block of color to the right side
 * of the stack and remove the leftmost color. The remaining
 * colors on the topmost layer of the stack are either added on
 * or reduced by one, depending on if they are on the right or
 * on the left side of the stack.
 * <p/>
 * If you are using this algorithm in your code please add
 * the following line:
 * Stack Blur Algorithm by Mario Klingemann <mario@quasimondo.com>
 */

public static Bitmap fastblur(Bitmap sentBitmap, float scale, int radius) {

    int width = Math.round(sentBitmap.getWidth() * scale);
    int height = Math.round(sentBitmap.getHeight() * scale);
    sentBitmap = Bitmap.createScaledBitmap(sentBitmap, width, height, false);

    Bitmap bitmap = sentBitmap.copy(sentBitmap.getConfig(), true);

    if (radius < 1) {
        return (null);
    }

    int w = bitmap.getWidth();
    int h = bitmap.getHeight();

    int[] pix = new int[w * h];
    Log.e("pix", w + " " + h + " " + pix.length);
    bitmap.getPixels(pix, 0, w, 0, 0, w, h);

    int wm = w - 1;
    int hm = h - 1;
    int wh = w * h;
    int div = radius + radius + 1;

    int r[] = new int[wh];
    int g[] = new int[wh];
    int b[] = new int[wh];
    int rsum, gsum, bsum, x, y, i, p, yp, yi, yw;
    int vmin[] = new int[Math.max(w, h)];

    int divsum = (div + 1) >> 1;
    divsum *= divsum;
    int dv[] = new int[256 * divsum];
    for (i = 0; i < 256 * divsum; i++) {
        dv[i] = (i / divsum);
    }

    yw = yi = 0;

    int[][] stack = new int[div][3];
    int stackpointer;
    int stackstart;
    int[] sir;
    int rbs;
    int r1 = radius + 1;
    int routsum, goutsum, boutsum;
    int rinsum, ginsum, binsum;

    for (y = 0; y < h; y++) {
        rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
        for (i = -radius; i <= radius; i++) {
            p = pix[yi + Math.min(wm, Math.max(i, 0))];
            sir = stack[i + radius];
            sir[0] = (p & 0xff0000) >> 16;
            sir[1] = (p & 0x00ff00) >> 8;
            sir[2] = (p & 0x0000ff);
            rbs = r1 - Math.abs(i);
            rsum += sir[0] * rbs;
            gsum += sir[1] * rbs;
            bsum += sir[2] * rbs;
            if (i > 0) {
                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];
            } else {
                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];
            }
        }
        stackpointer = radius;

        for (x = 0; x < w; x++) {

            r[yi] = dv[rsum];
            g[yi] = dv[gsum];
            b[yi] = dv[bsum];

            rsum -= routsum;
            gsum -= goutsum;
            bsum -= boutsum;

            stackstart = stackpointer - radius + div;
            sir = stack[stackstart % div];

            routsum -= sir[0];
            goutsum -= sir[1];
            boutsum -= sir[2];

            if (y == 0) {
                vmin[x] = Math.min(x + radius + 1, wm);
            }
            p = pix[yw + vmin[x]];

            sir[0] = (p & 0xff0000) >> 16;
            sir[1] = (p & 0x00ff00) >> 8;
            sir[2] = (p & 0x0000ff);

            rinsum += sir[0];
            ginsum += sir[1];
            binsum += sir[2];

            rsum += rinsum;
            gsum += ginsum;
            bsum += binsum;

            stackpointer = (stackpointer + 1) % div;
            sir = stack[(stackpointer) % div];

            routsum += sir[0];
            goutsum += sir[1];
            boutsum += sir[2];

            rinsum -= sir[0];
            ginsum -= sir[1];
            binsum -= sir[2];

            yi++;
        }
        yw += w;
    }
    for (x = 0; x < w; x++) {
        rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
        yp = -radius * w;
        for (i = -radius; i <= radius; i++) {
            yi = Math.max(0, yp) + x;

            sir = stack[i + radius];

            sir[0] = r[yi];
            sir[1] = g[yi];
            sir[2] = b[yi];

            rbs = r1 - Math.abs(i);

            rsum += r[yi] * rbs;
            gsum += g[yi] * rbs;
            bsum += b[yi] * rbs;

            if (i > 0) {
                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];
            } else {
                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];
            }

            if (i < hm) {
                yp += w;
            }
        }
        yi = x;
        stackpointer = radius;
        for (y = 0; y < h; y++) {
            // Preserve alpha channel: ( 0xff000000 & pix[yi] )
            pix[yi] = (0xff000000 & pix[yi]) | (dv[rsum] << 16) | (dv[gsum] << 8) | dv[bsum];

            rsum -= routsum;
            gsum -= goutsum;
            bsum -= boutsum;

            stackstart = stackpointer - radius + div;
            sir = stack[stackstart % div];

            routsum -= sir[0];
            goutsum -= sir[1];
            boutsum -= sir[2];

            if (x == 0) {
                vmin[y] = Math.min(y + r1, hm) * w;
            }
            p = x + vmin[y];

            sir[0] = r[p];
            sir[1] = g[p];
            sir[2] = b[p];

            rinsum += sir[0];
            ginsum += sir[1];
            binsum += sir[2];

            rsum += rinsum;
            gsum += ginsum;
            bsum += binsum;

            stackpointer = (stackpointer + 1) % div;
            sir = stack[stackpointer];

            routsum += sir[0];
            goutsum += sir[1];
            boutsum += sir[2];

            rinsum -= sir[0];
            ginsum -= sir[1];
            binsum -= sir[2];

            yi += w;
        }
    }

    Log.e("pix", w + " " + h + " " + pix.length);
    bitmap.setPixels(pix, 0, w, 0, 0, w, h);

    return (bitmap);
}

From source file:Main.java

public static Bitmap loadSizeLimitedBitmapFromUri(Uri imageUri, ContentResolver contentResolver) {
    try {//from  w  w w  . j  a v a2s  .c  om
        // Load the image into InputStream.
        InputStream imageInputStream = contentResolver.openInputStream(imageUri);

        // For saving memory, only decode the image meta and get the side length.
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        Rect outPadding = new Rect();
        BitmapFactory.decodeStream(imageInputStream, outPadding, options);

        // Calculate shrink rate when loading the image into memory.
        int maxSideLength = options.outWidth > options.outHeight ? options.outWidth : options.outHeight;
        options.inSampleSize = 1;
        options.inSampleSize = calculateSampleSize(maxSideLength, IMAGE_MAX_SIDE_LENGTH);
        options.inJustDecodeBounds = false;
        imageInputStream.close();

        // Load the bitmap and resize it to the expected size length
        imageInputStream = contentResolver.openInputStream(imageUri);
        Bitmap bitmap = BitmapFactory.decodeStream(imageInputStream, outPadding, options);
        maxSideLength = bitmap.getWidth() > bitmap.getHeight() ? bitmap.getWidth() : bitmap.getHeight();
        double ratio = IMAGE_MAX_SIDE_LENGTH / (double) maxSideLength;
        if (ratio < 1) {
            bitmap = Bitmap.createScaledBitmap(bitmap, (int) (bitmap.getWidth() * ratio),
                    (int) (bitmap.getHeight() * ratio), false);
        }

        return rotateBitmap(bitmap, getImageRotationAngle(imageUri, contentResolver));
    } catch (Exception e) {
        return null;
    }
}

From source file:Main.java

public static Bitmap loadSizeLimitedBitmapFromUri(Uri imageUri, ContentResolver contentResolver) {
    try {/* w  w  w.  j  av a2 s.c  o  m*/
        // Load the image into InputStream.
        InputStream imageInputStream = contentResolver.openInputStream(imageUri);

        // For saving memory, only decode the image meta and get the side length.
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        Rect outPadding = new Rect();
        BitmapFactory.decodeStream(imageInputStream, outPadding, options);

        // Calculate shrink rate when loading the image into memory.
        int maxSideLength = options.outWidth > options.outHeight ? options.outWidth : options.outHeight;
        options.inSampleSize = 1;
        options.inSampleSize = calculateSampleSize(maxSideLength, IMAGE_MAX_SIDE_LENGTH);
        options.inJustDecodeBounds = false;
        if (imageInputStream != null) {
            imageInputStream.close();
        }

        // Load the bitmap and resize it to the expected size length
        imageInputStream = contentResolver.openInputStream(imageUri);
        Bitmap bitmap = BitmapFactory.decodeStream(imageInputStream, outPadding, options);
        maxSideLength = bitmap.getWidth() > bitmap.getHeight() ? bitmap.getWidth() : bitmap.getHeight();
        double ratio = IMAGE_MAX_SIDE_LENGTH / (double) maxSideLength;
        if (ratio < 1) {
            bitmap = Bitmap.createScaledBitmap(bitmap, (int) (bitmap.getWidth() * ratio),
                    (int) (bitmap.getHeight() * ratio), false);
        }

        return rotateBitmap(bitmap, getImageRotationAngle(imageUri, contentResolver));
    } catch (Exception e) {
        return null;
    }
}

From source file:Main.java

public static Bitmap formatBitmap(Bitmap bitmap, int width, int height) {

    int wh = Math.max(bitmap.getWidth(), bitmap.getHeight());
    Bitmap mBitmap = Bitmap.createBitmap(wh, wh, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(mBitmap);
    canvas.drawBitmap(bitmap, -(bitmap.getWidth() - wh) / 2, -(bitmap.getHeight() - wh) / 2, null);
    bitmap = Bitmap.createScaledBitmap(mBitmap, width, height, true);
    return bitmap;
}

From source file:Main.java

/**
 * Resize a {@link Drawable} to the given size.<br />
 * Metrics and density are given by the {@link Resources} bount to this instance.
 * @param ctx Context./* ww  w .  j  ava2  s . c om*/
 * @param drawable {@link Drawable} to resize.
 * @param widthId Reference to the dimension containing the desired width.
 * @param heightId Reference to the dimension containing the desired height.
 * @return A scaled {@link Drawable}.
 */
public static Drawable resizeDrawable(Context ctx, Drawable drawable, int widthId, int heightId) {
    Resources res = ctx.getResources();
    //float density = res.getDisplayMetrics().density;

    //Get a bitmap from the drawable
    Bitmap bmp = drawableToBitmap(drawable);

    //Create a scaled bitmap
    //      bmp = Bitmap.createScaledBitmap(
    //            bmp,
    //            (int)(width * density),
    //            (int)(height * density),
    //            true);
    bmp = Bitmap.createScaledBitmap(bmp, res.getDimensionPixelSize(widthId),
            res.getDimensionPixelSize(heightId), true);

    //Convert bitmap to drawable
    return new BitmapDrawable(res, bmp);
}

From source file:Main.java

/**
 * Resize a bitmap object to fit the passed width and height
 * /*w w  w  .  jav  a2 s. co  m*/
 * @param input
 *           The bitmap to be resized
 * @param destWidth
 *           Desired maximum width of the result bitmap
 * @param destHeight
 *           Desired maximum height of the result bitmap
 * @return A new resized bitmap
 * @throws OutOfMemoryError
 *            if the operation exceeds the available vm memory
 */
public static Bitmap resizeBitmap(final Bitmap input, int destWidth, int destHeight, int rotation)
        throws OutOfMemoryError, Exception {

    int dstWidth = destWidth;
    int dstHeight = destHeight;
    final int srcWidth = input.getWidth();
    final int srcHeight = input.getHeight();

    if (rotation == 90 || rotation == 270) {
        dstWidth = destHeight;
        dstHeight = destWidth;
    }

    boolean needsResize = false;
    float p;
    if ((srcWidth > dstWidth) || (srcHeight > dstHeight)) {
        needsResize = true;
        if ((srcWidth > srcHeight) && (srcWidth > dstWidth)) {
            p = (float) dstWidth / (float) srcWidth;
            dstHeight = (int) (srcHeight * p);
        } else {
            p = (float) dstHeight / (float) srcHeight;
            dstWidth = (int) (srcWidth * p);
        }
    } else {
        dstWidth = srcWidth;
        dstHeight = srcHeight;
    }

    if (needsResize || rotation != 0) {
        Bitmap output;

        if (rotation == 0) {
            output = Bitmap.createScaledBitmap(input, dstWidth, dstHeight, true);
        } else {
            Matrix matrix = new Matrix();
            matrix.postScale((float) dstWidth / srcWidth, (float) dstHeight / srcHeight);
            matrix.postRotate(rotation);
            output = Bitmap.createBitmap(input, 0, 0, srcWidth, srcHeight, matrix, true);
        }
        return output;
    } else
        return input;
}

From source file:Main.java

public static Bitmap getDefaultArtwork(Context context, int id, int w, int h) {
    BitmapFactory.Options sBitmapOptionsCache = new BitmapFactory.Options();
    Bitmap b = null;/*from   w w w.  j  a v  a 2 s. c om*/
    int sampleSize = 1;

    sBitmapOptionsCache.inPreferredConfig = Bitmap.Config.ARGB_8888;

    // Compute the closest power-of-two scale factor 
    // and pass that to sBitmapOptionsCache.inSampleSize, which will
    // result in faster decoding and better quality
    sBitmapOptionsCache.inJustDecodeBounds = true;

    BitmapFactory.decodeResource(context.getResources(), id, sBitmapOptionsCache);
    int nextWidth = sBitmapOptionsCache.outWidth >> 1;
    int nextHeight = sBitmapOptionsCache.outHeight >> 1;
    while (nextWidth > w && nextHeight > h) {
        sampleSize <<= 1;
        nextWidth >>= 1;
        nextHeight >>= 1;
    }

    sBitmapOptionsCache.inSampleSize = sampleSize;
    sBitmapOptionsCache.inJustDecodeBounds = false;
    b = BitmapFactory.decodeResource(context.getResources(), id, sBitmapOptionsCache);

    if (b != null) {
        // finally rescale to exactly the size we need
        if (sBitmapOptionsCache.outWidth != w || sBitmapOptionsCache.outHeight != h) {
            Bitmap tmp = Bitmap.createScaledBitmap(b, w, h, true);
            // Bitmap.createScaledBitmap() can return the same bitmap
            if (tmp != b)
                b.recycle();
            b = tmp;
        }
    }

    return b;
}

From source file:Main.java

public static Bitmap resizeBitmap(Bitmap input, int destWidth, int destHeight, int rotation)
        throws OutOfMemoryError {
    int dstWidth = destWidth;
    int dstHeight = destHeight;
    int srcWidth = input.getWidth();
    int srcHeight = input.getHeight();

    if ((rotation == 90) || (rotation == 270)) {
        dstWidth = destHeight;/*from   w  w  w  . j ava  2 s .c  o  m*/
        dstHeight = destWidth;
    }

    boolean needsResize = false;

    if ((srcWidth > dstWidth) || (srcHeight > dstHeight)) {
        needsResize = true;

        float ratio1 = (float) srcWidth / dstWidth;
        float ratio2 = (float) srcHeight / dstHeight;
        Log.v("dsd", "ratio1:" + ratio1 + " ratio2:" + ratio2);

        if (ratio1 > ratio2) {
            float p = (float) dstWidth / srcWidth;
            dstHeight = (int) (srcHeight * p);
        } else {
            float p = (float) dstHeight / srcHeight;
            dstWidth = (int) (srcWidth * p);
        }
    } else {
        dstWidth = srcWidth;
        dstHeight = srcHeight;
    }

    Log.v("dsd", "dstWidth:" + dstWidth + " dstHeight:" + dstHeight + " srcWidth:" + srcWidth + " srcHeight:"
            + srcHeight);
    if ((needsResize) || (rotation != 0)) {
        Bitmap output = null;
        if (rotation == 0) {
            output = Bitmap.createScaledBitmap(input, dstWidth, dstHeight, true);
        } else {
            Matrix matrix = new Matrix();
            matrix.postScale((float) dstWidth / srcWidth, (float) dstHeight / srcHeight);
            matrix.postRotate(rotation);
            output = Bitmap.createBitmap(input, 0, 0, srcWidth, srcHeight, matrix, true);
        }
        return output;
    }
    return input;
}