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 getScaledScreenshot(final Activity activity, int scaleWidth, int scaleHeight,
        boolean relativeScaleIfTrue) {
    final View someView = activity.findViewById(android.R.id.content);
    final View rootView = someView.getRootView();
    final boolean originalCacheState = rootView.isDrawingCacheEnabled();
    rootView.setDrawingCacheEnabled(true);
    rootView.buildDrawingCache(true);/*  w  ww  .j  a  v  a 2s . co m*/

    // We could get a null or zero px bitmap if the rootView hasn't been measured
    // appropriately, or we grab it before layout.
    // This is ok, and we should handle it gracefully.
    final Bitmap original = rootView.getDrawingCache();
    Bitmap scaled = null;
    if (null != original && original.getWidth() > 0 && original.getHeight() > 0) {
        if (relativeScaleIfTrue) {
            scaleWidth = original.getWidth() / scaleWidth;
            scaleHeight = original.getHeight() / scaleHeight;
        }
        if (scaleWidth > 0 && scaleHeight > 0) {
            try {
                scaled = Bitmap.createScaledBitmap(original, scaleWidth, scaleHeight, false);
            } catch (OutOfMemoryError error) {
                Log.i(LOGTAG, "Not enough memory to produce scaled image, returning a null screenshot");
            }
        }
    }
    if (!originalCacheState) {
        rootView.setDrawingCacheEnabled(false);
    }
    return scaled;
}

From source file:Main.java

public static Bitmap bitmapLoad(Resources res, int resId, int width, int height) {

    // calc scale, load appropriately sampled bitmap from given resource

    BitmapFactory.Options resOptions = new BitmapFactory.Options();
    resOptions.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, resOptions);

    int resHeight = resOptions.outHeight;
    int resWidth = resOptions.outWidth;

    float xScale = (float) width / (float) resWidth;
    float yScale = (float) height / (float) resHeight;
    float scale = Math.max(xScale, yScale);
    if (scale > 1)

        if (width == 0)
            width = Math.round(resWidth / scale);
        else if (height == 0)
            height = Math.round(resHeight / scale);

    resOptions.inSampleSize = sampleSize(scale);
    resWidth /= resOptions.inSampleSize;
    resHeight /= resOptions.inSampleSize;
    resOptions.inJustDecodeBounds = false;

    Bitmap rawBitmap = BitmapFactory.decodeResource(res, resId, resOptions);

    // compare aspect ratio and crop

    rawBitmap = bitmapCrop(rawBitmap, width, height, resWidth, resHeight);

    // scale to desired size

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

From source file:Main.java

/** simple resizing of the given image to the desired width/height */
public static Bitmap getBitmapFromResource(Context ctx, int id, int x1, int y1) {
    BitmapDrawable bd = (BitmapDrawable) ctx.getResources().getDrawable(id);
    Bitmap b = bd.getBitmap();//from   w  w  w  .j ava  2 s  .  c om

    int x = b.getWidth();
    int y = b.getHeight();

    float scaleX = (float) x1 / x;
    float scaleY = (float) y1 / y;
    float scale = 1f;

    boolean scaleXInBounds = (scaleX * x) <= x1 && (scaleX * y) <= y1;
    boolean scaleYInBounds = (scaleY * x) <= x1 && (scaleY * y) <= y1;

    if (scaleXInBounds && scaleYInBounds) {
        scale = (scaleX > scaleY) ? scaleX : scaleY;
    } else if (scaleXInBounds) {
        scale = scaleX;
    } else if (scaleYInBounds) {
        scale = scaleY;
    }

    return Bitmap.createScaledBitmap(b, (int) (scale * x), (int) (scale * y), true);
}

From source file:Main.java

public static Bitmap scaleToFillBitmap(Bitmap dst, byte[] byImage) {
    Bitmap src = BitmapFactory.decodeByteArray(byImage, 0, byImage.length);

    float scaled = 1.0f;
    if ((float) dst.getWidth() / (float) src.getWidth() < (float) dst.getHeight() / (float) src.getHeight()) {
        scaled = (float) dst.getHeight() / (float) src.getHeight();
    } else {/*  w  w  w. ja  v  a2  s. c  o  m*/
        scaled = (float) dst.getWidth() / (float) src.getWidth();
    }

    Bitmap bmpScaled = Bitmap.createScaledBitmap(src, (int) Math.ceil(src.getWidth() * scaled),
            (int) Math.ceil(src.getHeight() * scaled), true);

    int offsetX = 0;
    int offsetY = 0;
    offsetX = bmpScaled.getWidth() - dst.getWidth() != 0 ? (bmpScaled.getWidth() - dst.getWidth()) / 2 : 0;
    offsetY = bmpScaled.getHeight() - dst.getHeight() != 0 ? (bmpScaled.getHeight() - dst.getHeight()) / 2 : 0;

    return Bitmap.createBitmap(bmpScaled, offsetX, offsetY, dst.getWidth(), dst.getHeight());
}

From source file:Main.java

public static Bitmap createIdenticon(byte[] hash, int background) {
    Bitmap identicon = Bitmap.createBitmap(5, 5, Bitmap.Config.ARGB_8888);

    float[] hsv = { Integer.valueOf(hash[3] + 128).floatValue() * 360.0f / 255.0f, 0.8f, 0.8f };
    int foreground = Color.HSVToColor(hsv);

    for (int x = 0; x < 5; x++) {
        //Enforce horizontal symmetry
        int i = x < 3 ? x : 4 - x;
        for (int y = 0; y < 5; y++) {
            int pixelColor;
            //toggle pixels based on bit being on/off
            if ((hash[i] >> y & 1) == 1)
                pixelColor = foreground;
            else//from  w ww  .  j ava2  s  .c o m
                pixelColor = background;
            identicon.setPixel(x, y, pixelColor);
        }
    }

    Bitmap bmpWithBorder = Bitmap.createBitmap(48, 48, identicon.getConfig());
    Canvas canvas = new Canvas(bmpWithBorder);
    canvas.drawColor(background);
    identicon = Bitmap.createScaledBitmap(identicon, 46, 46, false);
    canvas.drawBitmap(identicon, 1, 1, null);

    return bmpWithBorder;
}

From source file:Main.java

public static Bitmap scaleDownBitmap(Context context, Bitmap bitmap, int width) {
    /*/* w w  w.  j av  a2 s  .c  om*/
     * This method can lead to OutOfMemoryError!
     * If the source size is more than twice the target size use
     * the optimized version available in AudioUtil::readCoverBitmap
     */
    if (bitmap != null) {
        final float densityMultiplier = context.getResources().getDisplayMetrics().density;
        int w = (int) (width * densityMultiplier);
        int h = (int) (w * bitmap.getHeight() / ((double) bitmap.getWidth()));
        bitmap = Bitmap.createScaledBitmap(bitmap, w, h, true);
    }
    return bitmap;
}

From source file:Main.java

public static String writeBitmap(byte[] data, int cameraDegree, Rect rect, Rect willTransformRect)
        throws IOException {
    File file = new File(Environment.getExternalStorageDirectory() + "/bookclip/");
    file.mkdir();/* ww  w  .  j  a va 2 s .  c o  m*/
    String bitmapPath = file.getPath() + "/" + System.currentTimeMillis() + ".png";

    // bitmap rotation, scaling, crop
    BitmapFactory.Options option = new BitmapFactory.Options();
    option.inSampleSize = 2;
    Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, option);
    Matrix bitmapMatrix = new Matrix();
    bitmapMatrix.setRotate(cameraDegree);
    int x = rect.left, y = rect.top, width = rect.right - rect.left, height = rect.bottom - rect.top;
    Bitmap rotateBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), bitmapMatrix,
            false);
    // bitmap recycle
    bitmap.recycle();

    Bitmap scaledBitmap = Bitmap.createScaledBitmap(rotateBitmap, willTransformRect.right,
            willTransformRect.bottom - willTransformRect.top, false);
    // rotatebitmap recycle
    rotateBitmap.recycle();

    Bitmap cropBitmap = Bitmap.createBitmap(scaledBitmap, x, y, width, height, null, false);
    // scaledBitmap recycle
    scaledBitmap.recycle();

    // file write
    FileOutputStream fos = new FileOutputStream(new File(bitmapPath));
    cropBitmap.compress(CompressFormat.PNG, 100, fos);
    fos.flush();
    fos.close();

    // recycle
    cropBitmap.recycle();

    return bitmapPath;
}

From source file:Main.java

public static Drawable get_scaled_drawable_from_uri_string_for_square_container(Context context, String uri,
        int max_size) {
    Drawable drawable = null;/*from   ww w  .  ja  v  a2  s. co  m*/
    Uri img_uri = Uri.parse(uri);
    if (uri != null) {
        try {

            InputStream inputStream = context.getContentResolver().openInputStream(img_uri);
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            int sx = bitmap.getWidth();
            int sy = bitmap.getHeight();

            int fsx = max_size;
            int fsy = max_size;

            if (sy > sx)
                fsx = (int) ((float) max_size * ((float) sx / (float) sy));
            else if (sx > sy)
                fsy = (int) ((float) max_size * ((float) sy / (float) sx));

            Bitmap small_bitmap = Bitmap.createScaledBitmap(bitmap, fsx, fsy, false);
            bitmap.recycle();
            drawable = new BitmapDrawable(context.getResources(), small_bitmap);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
    return drawable;
}

From source file:Main.java

public static Bitmap makeSquare(File file, int cameraID) {
    int width;/*ww  w.  java 2  s.c  o m*/
    int height;
    Matrix matrix = new Matrix();
    Camera.CameraInfo info = new Camera.CameraInfo();
    Camera.getCameraInfo(cameraID, info);
    // Convert ByteArray to Bitmap

    Bitmap bitPic = decodeSampledBitmapFromFile(destinationFile.getAbsolutePath(), 800, 800);//BitmapFactory.decodeByteArray(data, 0, data.length);
    width = bitPic.getWidth();
    height = bitPic.getHeight();

    // Perform matrix rotations/mirrors depending on camera that took the photo
    if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
        float[] mirrorY = { -1, 0, 0, 0, 1, 0, 0, 0, 1 };
        Matrix matrixMirrorY = new Matrix();
        matrixMirrorY.setValues(mirrorY);

        matrix.postConcat(matrixMirrorY);
    }

    matrix.postRotate(90);

    // Create new Bitmap out of the old one
    Bitmap bitPicFinal = Bitmap.createBitmap(bitPic, 0, 0, width, height, matrix, true);
    bitPic.recycle();
    int desWidth;
    int desHeight;
    desWidth = bitPicFinal.getWidth();
    desHeight = desWidth;
    Bitmap croppedBitmap = Bitmap.createBitmap(bitPicFinal, 0,
            bitPicFinal.getHeight() / 2 - bitPicFinal.getWidth() / 2, desWidth, desHeight);
    croppedBitmap = Bitmap.createScaledBitmap(croppedBitmap, 528, 528, true);
    return croppedBitmap;
}

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./*from w ww .ja  v  a  2s .  c o  m*/
 * @param drawable {@link Drawable} to resize.
 * @param width Desired width in {@code dp}.
 * @param height Desired height in {@code dp}.
 * @return A scaled {@link Drawable}.
 */
public static Drawable resizeDrawable(Context ctx, Drawable drawable, int width, int height) {
    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);

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