android.graphics.Bitmap.createScaledBitmap()

Here are the examples of the java api android.graphics.Bitmap.createScaledBitmap() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

349 Examples 7

19 Source : MainActivity.java
with Apache License 2.0
from firebase

// [START function_scaleBitmapDown]
private Bitmap scaleBitmapDown(Bitmap bitmap, int maxDimension) {
    int originalWidth = bitmap.getWidth();
    int originalHeight = bitmap.getHeight();
    int resizedWidth = maxDimension;
    int resizedHeight = maxDimension;
    if (originalHeight > originalWidth) {
        resizedHeight = maxDimension;
        resizedWidth = (int) (resizedHeight * (float) originalWidth / (float) originalHeight);
    } else if (originalWidth > originalHeight) {
        resizedWidth = maxDimension;
        resizedHeight = (int) (resizedWidth * (float) originalHeight / (float) originalWidth);
    } else if (originalHeight == originalWidth) {
        resizedHeight = maxDimension;
        resizedWidth = maxDimension;
    }
    return Bitmap.createScaledBitmap(bitmap, resizedWidth, resizedHeight, false);
}

19 Source : ProfilePictureView.java
with Apache License 2.0
from eviltnan

private void setBlankProfilePicture() {
    // If we have a pending image download request cancel it
    if (lastRequest != null) {
        ImageDownloader.cancelRequest(lastRequest);
    }
    if (customizedDefaultProfilePicture == null) {
        int blankImageResource = isCropped() ? R.drawable.com_facebook_profile_picture_blank_square : R.drawable.com_facebook_profile_picture_blank_portrait;
        setImageBitmap(BitmapFactory.decodeResource(getResources(), blankImageResource));
    } else {
        // Update profile image dimensions.
        updateImageQueryParameters();
        // Resize inputBitmap to new dimensions of queryWidth and queryHeight.
        Bitmap scaledBitmap = Bitmap.createScaledBitmap(customizedDefaultProfilePicture, queryWidth, queryHeight, false);
        setImageBitmap(scaledBitmap);
    }
}

19 Source : PaintView.java
with GNU Affero General Public License v3.0
from EnricoPietrocola

public void scale(float maxW, float maxH, boolean filter) {
    float ratio = Math.min(maxW / mBitmap.getWidth(), maxH / mBitmap.getHeight());
    int width = Math.round((float) ratio * mBitmap.getWidth());
    int height = Math.round((float) ratio * mBitmap.getHeight());
    Bitmap newBitmap = Bitmap.createScaledBitmap(mBitmap, width, height, filter);
    mBitmap = newBitmap;
// return newBitmap;
}

19 Source : VusikView.java
with Apache License 2.0
from dynamitechetan

/**
 *        Resize every drawable to same size, else the size wil flicker randomly
 */
private Drawable resize(Drawable image) {
    Bitmap b = ((BitmapDrawable) image).getBitmap();
    Bitmap bitmapResized = Bitmap.createScaledBitmap(b, 96, 96, false);
    return new BitmapDrawable(getResources(), bitmapResized);
}

19 Source : WechatShareTools.java
with Apache License 2.0
from duboAndroid

public static void shareImage(Bitmap bitmap, SharePlace sharePlace) {
    WXImageObject wxImageObject = new WXImageObject(bitmap);
    WXMediaMessage msg = new WXMediaMessage();
    msg.mediaObject = wxImageObject;
    Bitmap thumbBmp = Bitmap.createScaledBitmap(bitmap, 100, 100, true);
    bitmap.recycle();
    msg.thumbData = RxImageTool.bitmap2Bytes(thumbBmp, Bitmap.CompressFormat.PNG);
    SendMessageToWX.Req req = new SendMessageToWX.Req();
    req.transaction = WechatPayTools.getCurrTime();
    req.message = msg;
    switch(sharePlace) {
        case Friend:
            req.scene = SendMessageToWX.Req.WXSceneSession;
            break;
        case Zone:
            req.scene = SendMessageToWX.Req.WXSceneTimeline;
            break;
        case Favorites:
            req.scene = SendMessageToWX.Req.WXSceneFavorite;
            break;
    }
    if (iwxapi != null) {
        iwxapi.sendReq(req);
    } else {
        throw new NullPointerException("请先调用WechatShare.init()方法");
    }
}

19 Source : ImageTools.java
with MIT License
from DrMint

/**
 * A function to scale a bitmap to a desired size.
 * @param bmp the image
 * @param width wanted width
 * @param height wanted height
 * @return new bitmap
 */
public static Bitmap scale(Bitmap bmp, int width, int height) {
    return Bitmap.createScaledBitmap(bmp, width, height, true);
}

19 Source : ImageTools.java
with MIT License
from DrMint

/**
 * A function to make a square bitmap.
 * @param bmp the image
 * @param newSize wanted size
 * @return a square bitmap
 */
@SuppressWarnings({ "SuspiciousNameCombination", "SameParameterValue" })
public static Bitmap toSquare(Bitmap bmp, int newSize) {
    int currentWidth = bmp.getWidth();
    int currentHeight = bmp.getHeight();
    int newWidth = currentWidth;
    int newHeight = currentHeight;
    int newX = 0;
    int newY = 0;
    if (currentWidth > currentHeight) {
        newWidth = currentHeight;
        newX = (currentWidth - currentHeight) / 2;
    } else {
        newHeight = currentWidth;
        newY = (currentHeight - currentWidth) / 2;
    }
    bmp = Bitmap.createBitmap(bmp, newX, newY, newWidth, newHeight);
    return Bitmap.createScaledBitmap(bmp, newSize, newSize, true);
}

19 Source : ImageTools.java
with MIT License
from DrMint

/**
 * A function to rescale a bitmap and make it fit into a square of side maxsize but keeping its ratio.
 * @param bmp the image
 * @param maxSize the maxsize of the width or the height
 * @return the resized image
 */
@SuppressWarnings("SameParameterValue")
public static Bitmap scaleToBeContainedInSquare(Bitmap bmp, int maxSize) {
    if (bmp.getHeight() > bmp.getWidth()) {
        return Bitmap.createScaledBitmap(bmp, bmp.getWidth() * maxSize / bmp.getHeight(), maxSize, true);
    } else {
        return Bitmap.createScaledBitmap(bmp, maxSize, bmp.getHeight() * maxSize / bmp.getWidth(), true);
    }
}

19 Source : FileInputOutput.java
with MIT License
from DrMint

public static Bitmap getBitmap(Resources resources, int index, int width, int height) {
    Bitmap bmp = getBitmap(resources, index);
    return Bitmap.createScaledBitmap(bmp, width, height, true);
}

19 Source : MainActivity.java
with BSD 2-Clause "Simplified" License
from drbfraser

private void gridButtonClicked(int col, int row) {
    Toast.makeText(this, "Button clicked: " + col + "," + row, Toast.LENGTH_SHORT).show();
    Button button = buttons[row][col];
    // Lock Button Sizes:
    lockButtonSizes();
    // Does not scale image.
    // button.setBackgroundResource(R.drawable.action_lock_pink);
    // Scale image to button: Only works in JellyBean!
    // Image from Crystal Clear icon set, under LGPL
    // http://commons.wikimedia.org/wiki/Crystal_Clear
    int newWidth = button.getWidth();
    int newHeight = button.getHeight();
    Bitmap originalBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.action_lock_pink);
    Bitmap scaledBitmap = Bitmap.createScaledBitmap(originalBitmap, newWidth, newHeight, true);
    Resources resource = getResources();
    button.setBackground(new BitmapDrawable(resource, scaledBitmap));
    // Change text on button:
    button.setText("" + col);
}

19 Source : ImageUtils.java
with GNU General Public License v3.0
from Donnnno

public static Bitmap bitmapLoad(Resources resources, int resId, int width, int height) {
    BitmapFactory.Options resOptions = new BitmapFactory.Options();
    resOptions.inJustDecodeBounds = true;
    // load appropriately sampled bitmap from given resource
    BitmapFactory.decodeResource(resources, 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 (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(resources, resId, resOptions);
    if (rawBitmap == null) {
        rawBitmap = Bitmap.createBitmap(resWidth, resHeight, Bitmap.Config.ARGB_8888);
    }
    // scale to desired size
    return Bitmap.createScaledBitmap(rawBitmap, width, height, true);
}

19 Source : ImageUtils.java
with MIT License
from DoFabien

/**
 * Resize an image to the given width and height. Leave one dimension 0 to
 * perform an aspect-ratio scale on the provided dimension.
 * @param bitmap
 * @param width
 * @param height
 * @return a new, scaled Bitmap
 */
public static Bitmap resize(Bitmap bitmap, final int width, final int height) {
    float aspect = bitmap.getWidth() / (float) bitmap.getHeight();
    if (width > 0 && height > 0) {
        return Bitmap.createScaledBitmap(bitmap, width, height, false);
    } else if (width > 0) {
        return Bitmap.createScaledBitmap(bitmap, width, (int) (width * 1 / aspect), false);
    } else if (height > 0) {
        return Bitmap.createScaledBitmap(bitmap, (int) (height * 1 / aspect), height, false);
    }
    return bitmap;
}

19 Source : ImageUtils.java
with GNU General Public License v3.0
from dkanada

public static Bitmap bitmapLoad(Resources resources, int resId, int width, int height) {
    BitmapFactory.Options resOptions = new BitmapFactory.Options();
    resOptions.inJustDecodeBounds = true;
    // load appropriately sampled bitmap from given resource
    BitmapFactory.decodeResource(resources, 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 (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(resources, resId, resOptions);
    if (rawBitmap == null) {
        rawBitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
    }
    // scale to desired size
    return Bitmap.createScaledBitmap(rawBitmap, width, height, true);
}

19 Source : NotificationPlatformBridge.java
with Apache License 2.0
from derry

/**
 * Ensures the availability of an icon for the notification.
 *
 * If |icon| is a valid, non-empty Bitmap, the bitmap will be scaled to be of an appropriate
 * size for the current Android device. Otherwise, a default icon will be created based on the
 * origin the notification is being displayed for.
 *
 * @param icon The developer-provided icon they intend to use for the notification.
 * @param origin The origin the notification is being displayed for.
 * @return An appropriately sized icon to use for the notification.
 */
@VisibleForTesting
public Bitmap ensureNormalizedIcon(Bitmap icon, String origin) {
    if (icon == null || icon.getWidth() == 0) {
        if (mIconGenerator == null) {
            int cornerRadiusPx = Math.min(mLargeIconWidthPx, mLargeIconHeightPx) / 2;
            mIconGenerator = new RoundedIconGenerator(mLargeIconWidthPx, mLargeIconHeightPx, cornerRadiusPx, NOTIFICATION_ICON_BG_COLOR, NOTIFICATION_TEXT_SIZE_DP * mDensity);
        }
        return mIconGenerator.generateIconForUrl(origin, true);
    }
    if (icon.getWidth() > mLargeIconWidthPx || icon.getHeight() > mLargeIconHeightPx) {
        return icon.createScaledBitmap(icon, mLargeIconWidthPx, mLargeIconHeightPx, false);
    }
    return icon;
}

19 Source : ImageUtil.java
with GNU General Public License v3.0
from deepshooter

public static Bitmap getResizedBitmap(Bitmap image, int maxSize) {
    int width = image.getWidth();
    int height = image.getHeight();
    float bitmapRatio = (float) width / (float) height;
    if (bitmapRatio > 1) {
        width = maxSize;
        height = (int) (width / bitmapRatio);
    } else {
        height = maxSize;
        width = (int) (height * bitmapRatio);
    }
    return Bitmap.createScaledBitmap(image, width, height, true);
}

19 Source : Utils.java
with Apache License 2.0
from deepaktwr

/* public static final int COMMENT_TRANSPARENCY_PERCENT = 70;
    public static float MIN_WIDTH = 300;
    public static float MIN_HIGHT = 300;
    public static float MAX_WIDTH = 700;
    public static float MAX_HEIGHT = 900;
    //show be less than or equal to 4 for now
    public static int MAX_IMAGES_TO_SHOW = 4;
    */
/*public static final float MIN_RATIO = 0.3f;
    public static final float MAX_RATIO = 0.7f;*/
/*
    public static final float MIN_ADD_RATIO = 0.25f;
    //for add in layout
    public static boolean shouldShowAddInLayout(){
        return false;
    }
    //for comments
    public static boolean shouldShowComments(){
        return false;
    }
    public static boolean showShowDivider(){
        return true;
    }
    public static ColorCombination getColorCombo(){
        return ColorCombination.VIBRANT_TO_MUTED;
    }
    //for image
    public static int getErrorDrawableId(){
        return 0;
    }
    public static ImageView.ScaleType getImageScaleType(){
        return ImageView.ScaleType.CENTER_CROP;
    }*/
public static BeanBitmapResult getScaledResult(Bitmap bitmap, int reqWidth, int reqHeight) throws FrameException {
    if (bitmap == null || reqWidth == 0 || reqHeight == 0)
        throw new IllegalArgumentException("scaling can not perform on invalid arguments");
    BeanBitmapResult beanBitmapResult = new BeanBitmapResult();
    beanBitmapResult.setHeight(bitmap.getHeight());
    beanBitmapResult.setWidth(bitmap.getWidth());
    int inSampleSize = 1;
    if (beanBitmapResult.getHeight() > reqHeight || beanBitmapResult.getWidth() > reqWidth) {
        final int heightRatio = Math.round((float) beanBitmapResult.getHeight() / (float) reqHeight);
        final int widthRatio = Math.round((float) beanBitmapResult.getWidth() / (float) reqWidth);
        inSampleSize = (heightRatio <= widthRatio && beanBitmapResult.getHeight() > reqHeight) ? heightRatio : (widthRatio <= heightRatio && beanBitmapResult.getWidth() > reqWidth) ? widthRatio : 1;
    }
    if (inSampleSize == 0)
        inSampleSize = 1;
    Bitmap btmp = Bitmap.createScaledBitmap(bitmap, beanBitmapResult.getWidth() / inSampleSize, beanBitmapResult.getHeight() / inSampleSize, false);
    beanBitmapResult.setBitmap(btmp);
    Utils.logMessage("width : " + reqWidth + " height : " + reqHeight);
    Utils.logMessage("width : " + beanBitmapResult.getWidth() + " height : " + beanBitmapResult.getHeight());
    Utils.logMessage("width : " + beanBitmapResult.getWidth() / inSampleSize + " height : " + beanBitmapResult.getHeight() / inSampleSize);
    return beanBitmapResult;
}

19 Source : LoadImage.java
with Apache License 2.0
from dbbahnhoflive

@Override
protected void onPostExecute(Bitmap bitmap) {
    if (bitmap != null) {
        float ascpect = (float) bitmap.getWidth() / (float) bitmap.getHeight();
        Log.e("KK", "w " + width + "  asp " + ascpect);
        Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, width, (int) (width / ascpect), true);
        BitmapDrawable d = new BitmapDrawable(textView.getContext().getResources(), scaledBitmap);
        mDrawable.addLevel(1, 1, d);
        mDrawable.setBounds(0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight());
        mDrawable.setLevel(1);
        // i don't know yet a better way to refresh TextView
        // mTv.invalidate() doesn't work as expected
        CharSequence t = textView.getText();
        textView.setText(t);
    }
}

19 Source : MultiStateSwitch.java
with Apache License 2.0
from davidmigloz

/**
 * Creates a bitmap representing the shadow of given bitmap.
 */
private Bitmap createShadow(@NonNull Bitmap bitmap, int blurRadius) {
    Bitmap shadow = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth(), bitmap.getHeight(), false);
    Paint shadowPaint = new Paint();
    shadowPaint.setMaskFilter(new BlurMaskFilter(blurRadius, BlurMaskFilter.Blur.NORMAL));
    int[] offsetXY = new int[2];
    return shadow.extractAlpha(shadowPaint, offsetXY);
}

19 Source : ImageUtils.java
with GNU General Public License v3.0
from Davarco

public static Bitmap getResizedBitmap(Bitmap bm, int newWidth, int newHeight) {
    return Bitmap.createScaledBitmap(bm, newWidth, newHeight, false);
}

19 Source : SettingView.java
with MIT License
from congshengwu

private Bitmap createScaleBitmap(Bitmap bitmap, int w, int h) {
    return Bitmap.createScaledBitmap(bitmap, w, h, false);
}

19 Source : CalibrationSurfaceView.java
with MIT License
from congshengwu

private Bitmap createScaleBitmap(Bitmap bitmap) {
    return Bitmap.createScaledBitmap(bitmap, (int) (getScreenW() / 20), (int) (getScreenW() / 20), // 设置“设置”按钮尺寸为96*96(1080p) 比例
    false);
}

19 Source : Images.java
with GNU General Public License v3.0
from cgeo

public static Bitmap resizeBitmap(Bitmap bmp, int newWidth, int newHeight) {
    if (bmp == null || newWidth <= 0 || bmp.getWidth() == newWidth)
        return bmp;
    return Bitmap.createScaledBitmap(bmp, newWidth, newHeight, true);
}

19 Source : MainActivity.java
with Apache License 2.0
from byvlstr

private Bitmap getSmallerImage(int drawableId) {
    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), drawableId);
    int newHeight = (int) (bitmap.getHeight() * (1000.0 / bitmap.getWidth()));
    Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 1000, newHeight, true);
    return scaled;
}

19 Source : ChipSpan.java
with Apache License 2.0
from btcontract

private Bitmap scaleDown(Bitmap realImage, float maxImageSize, boolean filter) {
    float ratio = Math.min(maxImageSize / realImage.getWidth(), maxImageSize / realImage.getHeight());
    int width = Math.round(ratio * realImage.getWidth());
    int height = Math.round(ratio * realImage.getHeight());
    return Bitmap.createScaledBitmap(realImage, width, height, filter);
}

19 Source : BitmapHelper.java
with GNU General Public License v3.0
from beemdevelopment

/**
 * Scales the given Bitmap to the given maximum width/height, while keeping the aspect ratio intact.
 */
public static Bitmap resize(Bitmap bitmap, int maxWidth, int maxHeight) {
    if (maxHeight <= 0 || maxWidth <= 0) {
        return bitmap;
    }
    float maxRatio = (float) maxWidth / maxHeight;
    float ratio = (float) bitmap.getWidth() / bitmap.getHeight();
    int width = maxWidth;
    int height = maxHeight;
    if (maxRatio > 1) {
        width = (int) ((float) maxHeight * ratio);
    } else {
        height = (int) ((float) maxWidth / ratio);
    }
    return Bitmap.createScaledBitmap(bitmap, width, height, true);
}

19 Source : BitmapUtils.java
with Apache License 2.0
from BCsl

private static Bitmap createScaleBitmap(Bitmap tempBitmap, int desiredWidth, int desiredHeight) {
    // If necessary, scale down to the maximal acceptable size.
    if (tempBitmap != null && (tempBitmap.getWidth() > desiredWidth || tempBitmap.getHeight() > desiredHeight)) {
        Bitmap bitmap = Bitmap.createScaledBitmap(tempBitmap, desiredWidth, desiredHeight, true);
        tempBitmap.recycle();
        return bitmap;
    } else {
        return tempBitmap;
    }
}

19 Source : BitmapUtils.java
with Apache License 2.0
from ayaseruri

public static Bitmap scale(Bitmap bitmap, int pixelW, int pixelH) {
    return Bitmap.createScaledBitmap(bitmap, pixelW, pixelH, true);
}

19 Source : FileUtils.java
with GNU General Public License v3.0
from ashomokdev

public static Bitmap scaleBitmapDown(Bitmap bitmap, int maxDimension) {
    int originalWidth = bitmap.getWidth();
    int originalHeight = bitmap.getHeight();
    int resizedWidth = maxDimension;
    int resizedHeight = maxDimension;
    if (originalHeight > originalWidth) {
        resizedHeight = maxDimension;
        resizedWidth = (int) (resizedHeight * (float) originalWidth / (float) originalHeight);
    } else if (originalWidth > originalHeight) {
        resizedWidth = maxDimension;
        resizedHeight = (int) (resizedWidth * (float) originalHeight / (float) originalWidth);
    } else if (originalHeight == originalWidth) {
        resizedHeight = maxDimension;
        resizedWidth = maxDimension;
    }
    return Bitmap.createScaledBitmap(bitmap, resizedWidth, resizedHeight, false);
}

19 Source : ResizeTransformation.java
with Apache License 2.0
from arcus-smart-home

@Override
public Bitmap transform(@NonNull Bitmap image) {
    if (maxHeight > 0 && maxWidth > 0) {
        int width = image.getWidth();
        int height = image.getHeight();
        float ratioBitmap = (float) width / (float) height;
        float ratioMax = (float) maxWidth / (float) maxHeight;
        int finalWidth = maxWidth;
        int finalHeight = maxHeight;
        if (ratioMax > 1) {
            finalWidth = (int) ((float) maxHeight * ratioBitmap);
        } else {
            finalHeight = (int) ((float) maxWidth / ratioBitmap);
        }
        Bitmap resizedImage = Bitmap.createScaledBitmap(image, finalWidth, finalHeight, true);
        if (image != resizedImage && !image.isRecycled()) {
            image.recycle();
        }
        return resizedImage;
    } else {
        return image;
    }
}

19 Source : UploadNewsFeedActivity.java
with GNU General Public License v3.0
from appteam-nith

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
        Uri filePath = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor c = getContentResolver().query(filePath, filePathColumn, null, null, null);
        c.moveToFirst();
        String imgDecodableString = c.getString(c.getColumnIndex(filePathColumn[0]));
        c.close();
        Bitmap bitmap = BitmapFactory.decodeFile(imgDecodableString);
        Bitmap bitmap1 = Bitmap.createScaledBitmap(bitmap, getWindow().getWindowManager().getDefaultDisplay().getWidth() / 2, getWindow().getWindowManager().getDefaultDisplay().getHeight() / 2, true);
        editorView.addImage(bitmap1);
    }
}

19 Source : BlurTool.java
with Apache License 2.0
from apache

/**
 * radius in [0,10]
 */
@NonNull
@SuppressWarnings("unused")
public static Bitmap blur(@NonNull Bitmap originalImage, int radius) {
    long start = System.currentTimeMillis();
    // [0,10]
    radius = Math.min(10, Math.max(0, radius));
    if (radius == 0) {
        return originalImage;
    }
    int width = originalImage.getWidth();
    int height = originalImage.getHeight();
    if (width <= 0 || height <= 0) {
        return originalImage;
    }
    double sampling = calculateSampling(radius);
    int retryTimes = 3;
    Bitmap sampledImage = Bitmap.createScaledBitmap(originalImage, (int) (sampling * width), (int) (sampling * height), true);
    for (int i = 0; i < retryTimes; i++) {
        try {
            if (radius == 0) {
                return originalImage;
            }
            double s = calculateSampling(radius);
            if (s != sampling) {
                sampling = s;
                sampledImage = Bitmap.createScaledBitmap(originalImage, (int) (sampling * width), (int) (sampling * height), true);
            }
            Bitmap result = stackBlur(sampledImage, radius);
            return result;
        } catch (Exception e) {
            WXLogUtils.e(TAG, "thrown exception when blurred image(times = " + i + ")," + e.getMessage());
            radius -= 1;
            radius = Math.max(0, radius);
        }
    }
    WXLogUtils.d(TAG, "elapsed time on blurring image(radius:" + radius + ",sampling: " + sampling + "): " + (System.currentTimeMillis() - start) + "ms");
    return originalImage;
}

19 Source : RNImageToPdf.java
with MIT License
from Anyline

private Bitmap resize(Bitmap bitmap, int maxWidth, int maxHeight) {
    if (maxWidth == 0 || maxHeight == 0)
        return bitmap;
    if (bitmap.getWidth() <= maxWidth && bitmap.getHeight() <= maxHeight)
        return bitmap;
    double aspectRatio = (double) bitmap.getHeight() / bitmap.getWidth();
    int height = Math.round(maxWidth * aspectRatio) < maxHeight ? (int) Math.round(maxWidth * aspectRatio) : maxHeight;
    int width = (int) Math.round(height / aspectRatio);
    return Bitmap.createScaledBitmap(bitmap, width, height, true);
}

19 Source : PrinterUtil.java
with Apache License 2.0
from anggastudio

private Bitmap scaledBitmap(Bitmap bitmap, int width) {
    try {
        int desiredWidth = width == 0 || bitmap.getWidth() <= PRINTER_WIDTH ? bitmap.getWidth() : PRINTER_WIDTH;
        if (width > 0 && width <= PRINTER_WIDTH) {
            desiredWidth = width;
        }
        int height;
        float scale = (float) desiredWidth / (float) bitmap.getWidth();
        height = (int) (bitmap.getHeight() * scale);
        return Bitmap.createScaledBitmap(bitmap, desiredWidth, height, true);
    } catch (NullPointerException e) {
        Log.e(TAG, "Maybe resource is vector or mipmap?");
        return null;
    }
}

19 Source : MotionLabel.java
with Apache License 2.0
from androidx

Bitmap blur(Bitmap bitmapOriginal, int factor) {
    Long t = System.nanoTime();
    int w = bitmapOriginal.getWidth();
    int h = bitmapOriginal.getHeight();
    w /= 2;
    h /= 2;
    Bitmap ret = Bitmap.createScaledBitmap(bitmapOriginal, w, h, true);
    for (int i = 0; i < factor; i++) {
        if (w < 32 || h < 32) {
            break;
        }
        w /= 2;
        h /= 2;
        ret = Bitmap.createScaledBitmap(ret, w, h, true);
    }
    return ret;
}

19 Source : StreamingTextView.java
with Apache License 2.0
from androidx

private Bitmap getScaledBitmap(int resourceId, float scaled) {
    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resourceId);
    return Bitmap.createScaledBitmap(bitmap, (int) (bitmap.getWidth() * scaled), (int) (bitmap.getHeight() * scaled), false);
}

19 Source : ActivitySelfieSwap.java
with Apache License 2.0
from androidroadies

/**
 * Returns a resized bitmap of bm,
 */
private Bitmap resizeBitmap(Bitmap bm) {
    int h = bm.getHeight();
    int w = bm.getWidth();
    int maxSize = 1200;
    if (h == w) {
        h = maxSize;
        w = maxSize;
    } else if (h > w) {
        float ratio = (float) w / (float) h;
        h = maxSize;
        w = (int) (maxSize * ratio);
    } else {
        float ratio = (float) h / w;
        w = maxSize;
        h = (int) (maxSize * ratio);
    }
    Bitmap resizedBitmap = Bitmap.createScaledBitmap(bm, w, h, true);
    return resizedBitmap;
}

19 Source : PieChart.java
with GNU General Public License v3.0
from AndreAle94

private Bitmap scaleIcon(Bitmap source, float iconRadius) {
    int size = (int) (iconRadius * 2);
    return Bitmap.createScaledBitmap(source, size, size, false);
}

19 Source : AlbumTagEditorActivity.java
with GNU General Public License v3.0
from aliumujib

private static Bitmap getResizedAlbumCover(@NonNull Bitmap src, int maxForSmallerSize) {
    int width = src.getWidth();
    int height = src.getHeight();
    final int dstWidth;
    final int dstHeight;
    if (width < height) {
        if (maxForSmallerSize >= width) {
            return src;
        }
        float ratio = (float) height / width;
        dstWidth = maxForSmallerSize;
        dstHeight = Math.round(maxForSmallerSize * ratio);
    } else {
        if (maxForSmallerSize >= height) {
            return src;
        }
        float ratio = (float) width / height;
        dstWidth = Math.round(maxForSmallerSize * ratio);
        dstHeight = maxForSmallerSize;
    }
    return Bitmap.createScaledBitmap(src, dstWidth, dstHeight, false);
}

19 Source : Utils.java
with Apache License 2.0
from AlirezaGhanbarinia

static Bitmap scaleDown(Bitmap realImage) {
    float ratio = Math.min((float) 1000 / realImage.getWidth(), (float) 1000 / realImage.getHeight());
    int width = Math.round(ratio * realImage.getWidth());
    int height = Math.round(ratio * realImage.getHeight());
    return Bitmap.createScaledBitmap(realImage, width, height, true);
}

19 Source : Utils.java
with Apache License 2.0
from AlirezaGhanbarinia

public static Bitmap scaleDown(Bitmap realImage) {
    float ratio = Math.min(1000.0F / (float) realImage.getWidth(), 1000.0F / (float) realImage.getHeight());
    int width = Math.round(ratio * (float) realImage.getWidth());
    int height = Math.round(ratio * (float) realImage.getHeight());
    return Bitmap.createScaledBitmap(realImage, width, height, true);
}

19 Source : ImageUtils.java
with Apache License 2.0
from alex011235

/**
 * Returns a resized version of bm.
 *
 * @param bm input image to resize.
 * @return resized bitmap bm.
 */
static Bitmap resizeBitmap(Bitmap bm) {
    int h = bm.getHeight();
    int w = bm.getWidth();
    if (h == w) {
        h = MAXIMUM_IMAGE_SIZE;
        w = MAXIMUM_IMAGE_SIZE;
    } else if (h > w) {
        float ratio = (float) w / (float) h;
        h = MAXIMUM_IMAGE_SIZE;
        w = (int) (MAXIMUM_IMAGE_SIZE * ratio);
    } else {
        float ratio = (float) h / w;
        w = MAXIMUM_IMAGE_SIZE;
        h = (int) (MAXIMUM_IMAGE_SIZE * ratio);
    }
    return Bitmap.createScaledBitmap(bm, w, h, true);
}

19 Source : Utility.java
with Apache License 2.0
from akshay2211

public static Bitmap getScaledBitmap(int maxWidth, Bitmap rotatedBitmap) {
    try {
        int nh = (int) (rotatedBitmap.getHeight() * (512.0 / rotatedBitmap.getWidth()));
        return Bitmap.createScaledBitmap(rotatedBitmap, maxWidth, nh, true);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

19 Source : PrintPreview.java
with Apache License 2.0
from Aevi-UK

/**
 * Returns a scaled bitmap that will be scaled according to the current screen/display. This bitmap when displayed on the screen will have a
 * size equal to the physical size of the printout according to the parameter in {@link PrinterSettings#getPrintableWidth()} (in mm).
 *
 * @param context The current Android context
 * @return A scaled bitmap that can be shown on the screen to provide an indication of what the exact printout will look like
 */
public Bitmap getScaledBitmap(Context context) {
    cursor = VERTICAL_MARGIN;
    DisplayMetrics metrics = context.getResources().getDisplayMetrics();
    Bitmap bitmap = getBitmap();
    // convert from dpi to dpmm
    float pxPerMm = metrics.xdpi / 25.4f;
    int width = bitmap.getWidth();
    float scale = (printerSettings.getPrintableWidth() * pxPerMm) / (float) width;
    return Bitmap.createScaledBitmap(bitmap, (int) (bitmap.getWidth() * scale), (int) (bitmap.getHeight() * scale), true);
}

18 Source : CameraLauncher.java
with MIT License
from Zeta36

/**
 * Return a scaled bitmap based on the target width and height
 *
 * @param imagePath
 * @return
 * @throws IOException
 */
private Bitmap getScaledBitmap(String imageUrl) throws IOException {
    // If no new width or height were specified return the original bitmap
    if (this.targetWidth <= 0 && this.targetHeight <= 0) {
        InputStream fileStream = null;
        Bitmap image = null;
        try {
            fileStream = FileHelper.getInputStreamFromUriString(imageUrl, cordova);
            image = BitmapFactory.decodeStream(fileStream);
        } finally {
            if (fileStream != null) {
                try {
                    fileStream.close();
                } catch (IOException e) {
                    LOG.d(LOG_TAG, "Exception while closing file input stream.");
                }
            }
        }
        return image;
    }
    // figure out the original width and height of the image
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    InputStream fileStream = null;
    try {
        fileStream = FileHelper.getInputStreamFromUriString(imageUrl, cordova);
        BitmapFactory.decodeStream(fileStream, null, options);
    } finally {
        if (fileStream != null) {
            try {
                fileStream.close();
            } catch (IOException e) {
                LOG.d(LOG_TAG, "Exception while closing file input stream.");
            }
        }
    }
    // CB-2292: WTF? Why is the width null?
    if (options.outWidth == 0 || options.outHeight == 0) {
        return null;
    }
    // determine the correct aspect ratio
    int[] widthHeight = calculateAspectRatio(options.outWidth, options.outHeight);
    // Load in the smallest bitmap possible that is closest to the size we want
    options.inJustDecodeBounds = false;
    options.inSampleSize = calculateSampleSize(options.outWidth, options.outHeight, this.targetWidth, this.targetHeight);
    Bitmap unscaledBitmap = null;
    try {
        fileStream = FileHelper.getInputStreamFromUriString(imageUrl, cordova);
        unscaledBitmap = BitmapFactory.decodeStream(fileStream, null, options);
    } finally {
        if (fileStream != null) {
            try {
                fileStream.close();
            } catch (IOException e) {
                LOG.d(LOG_TAG, "Exception while closing file input stream.");
            }
        }
    }
    if (unscaledBitmap == null) {
        return null;
    }
    return Bitmap.createScaledBitmap(unscaledBitmap, widthHeight[0], widthHeight[1], true);
}

18 Source : ImageUtils.java
with MIT License
from yuriy-budiyev

/**
 * Scale image to fit specified frame ({@code resultWidth} x {@code resultHeight}).
 * If specified {@code resultWidth} and {@code resultHeight} are the same as the current
 * width and height of the source image, the source image will be returned.
 *
 * @param image        Source image
 * @param resultWidth  Result width
 * @param resultHeight Result height
 * @param upscale      Upscale image if it is smaller than the frame
 * @return Scaled image or original image
 */
@NonNull
public static Bitmap scaleToFit(@NonNull final Bitmap image, final int resultWidth, final int resultHeight, final boolean upscale) {
    final int sourceWidth = image.getWidth();
    final int sourceHeight = image.getHeight();
    if (sourceWidth == resultWidth && sourceHeight == resultHeight) {
        return image;
    }
    if (!upscale && sourceWidth < resultWidth && sourceHeight < resultHeight) {
        return image;
    }
    final int sourceDivisor = greatestCommonDivisor(sourceWidth, sourceHeight);
    final int sourceRatioWidth = sourceWidth / sourceDivisor;
    final int sourceRatioHeight = sourceHeight / sourceDivisor;
    final int resultDivisor = greatestCommonDivisor(resultWidth, resultHeight);
    final int resultRatioWidth = resultWidth / resultDivisor;
    final int resultRatioHeight = resultHeight / resultDivisor;
    if (sourceRatioWidth == resultRatioWidth && sourceRatioHeight == resultRatioHeight) {
        return Bitmap.createScaledBitmap(image, resultWidth, resultHeight, true);
    }
    final int fitWidth = sourceRatioWidth * resultHeight / sourceRatioHeight;
    if (fitWidth > resultWidth) {
        if (sourceWidth == resultWidth) {
            return image;
        } else {
            final int fitHeight = sourceRatioHeight * resultWidth / sourceRatioWidth;
            return Bitmap.createScaledBitmap(image, resultWidth, fitHeight, true);
        }
    } else {
        if (sourceHeight == resultHeight) {
            return image;
        } else {
            return Bitmap.createScaledBitmap(image, fitWidth, resultHeight, true);
        }
    }
}

18 Source : ImageFilterDownsample.java
with Apache License 2.0
from yuchuangu85

@Override
public Bitmap apply(Bitmap bitmap, float scaleFactor, int quality) {
    if (getParameters() == null) {
        return bitmap;
    }
    int w = bitmap.getWidth();
    int h = bitmap.getHeight();
    int p = getParameters().getValue();
    // size of original precached image
    Rect size = MasterImage.getImage().getOriginalBounds();
    int orig_w = size.width();
    int orig_h = size.height();
    if (p > 0 && p < 100) {
        // scale preview to same size as the resulting bitmap from a "save"
        int newWidth = orig_w * p / 100;
        int newHeight = orig_h * p / 100;
        // only scale preview if preview isn't already scaled enough
        if (newWidth <= 0 || newHeight <= 0 || newWidth >= w || newHeight >= h) {
            return bitmap;
        }
        Bitmap ret = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
        if (ret != bitmap) {
            bitmap.recycle();
        }
        return ret;
    }
    return bitmap;
}

18 Source : CustomBlur.java
with Apache License 2.0
from yangchong211

@SuppressLint("NewApi")
public static Bitmap apply(Context context, @NonNull Bitmap sentBitmap, int radius) {
    Bitmap bitmap = Bitmap.createScaledBitmap(sentBitmap, sentBitmap.getWidth() / 2, sentBitmap.getHeight() / 2, false);
    if (VERSION.SDK_INT > 16) {
        final RenderScript rs = RenderScript.create(context);
        final Allocation input = Allocation.createFromBitmap(rs, bitmap, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT);
        final Allocation output = Allocation.createTyped(rs, input.getType());
        final ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
        script.setRadius(radius);
        script.setInput(input);
        script.forEach(output);
        output.copyTo(bitmap);
        // After finishing everything, we destroy the Renderscript.
        rs.destroy();
        return bitmap;
    }
    if (radius < 1) {
        return (null);
    }
    int w = bitmap.getWidth();
    int h = bitmap.getHeight();
    int[] pix = new int[w * h];
    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;
        }
    }
    bitmap.setPixels(pix, 0, w, 0, 0, w, h);
    return (bitmap);
}

18 Source : ResultActivity.java
with GNU General Public License v3.0
from YangChengTeam

private void sharePhotoToWeChat() {
    // 第一步:判读图像文件是否存在
    // String path ="/storage/emulated/0/image/123.jpg";
    String path = mFilePath;
    File file = new File(path);
    if (!file.exists()) {
        Toast.makeText(ResultActivity.this, "文件不存在", Toast.LENGTH_SHORT).show();
    }
    // 第二步:创建WXImageObject,
    WXImageObject imgObj = new WXImageObject();
    // 设置文件的路径
    imgObj.setImagePath(path);
    // 第三步:创建WXMediaMessage对象,并包装WXimageObjext对象
    WXMediaMessage msg = new WXMediaMessage();
    msg.mediaObject = imgObj;
    // 第四步:压缩图片
    Bitmap bitmap = BitmapFactory.decodeFile(path);
    Bitmap thumBitmap = bitmap.createScaledBitmap(bitmap, 120, 150, true);
    // 释放图片占用的内存资源
    bitmap.recycle();
    // 压缩图
    msg.thumbData = bitmapToByteArray(thumBitmap, true);
    // 第五步:创建SendMessageTo.Req对象,发送数据
    SendMessageToWX.Req req = new SendMessageToWX.Req();
    // 唯一标识
    req.transaction = buildTransaction("img");
    // 发送的内容或者对象
    req.message = msg;
    // req.scene = send_friend.isChecked() ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
    req.scene = SendMessageToWX.Req.WXSceneSession;
    mMsgApi.sendReq(req);
}

18 Source : BlurDrawable.java
with GNU General Public License v3.0
from YangChengTeam

public static Bitmap rsBlur(Context context, Bitmap source, int radius) {
    int width = Math.round(source.getWidth() * 1f / 4);
    int height = Math.round(source.getHeight() * 1f / 4);
    Bitmap inputBmp = Bitmap.createScaledBitmap(source, width, height, false);
    // (1)
    RenderScript renderScript = RenderScript.create(context);
    // Log.i("TAG", "scale size:" + source.getWidth() + "*" + source.getHeight());
    // Allocate memory for Renderscript to work with
    // (2)
    final Allocation input = Allocation.createFromBitmap(renderScript, inputBmp);
    final Allocation output = Allocation.createTyped(renderScript, input.getType());
    // (3)
    // Load up an instance of the specific script that we want to use.
    ScriptIntrinsicBlur scriptIntrinsicBlur = ScriptIntrinsicBlur.create(renderScript, Element.U8_4(renderScript));
    // (4)
    scriptIntrinsicBlur.setInput(input);
    // (5)
    // Set the blur radius
    scriptIntrinsicBlur.setRadius(radius);
    // (6)
    // Start the ScriptIntrinisicBlur
    scriptIntrinsicBlur.forEach(output);
    // (7)
    // Copy the output to the blurred bitmap
    output.copyTo(inputBmp);
    // (8)
    renderScript.destroy();
    return inputBmp;
}

18 Source : QRCodeProduceUtils.java
with Apache License 2.0
from xuexiangjys

private static int getDominantColor(Bitmap bitmap) {
    Bitmap newBitmap = Bitmap.createScaledBitmap(bitmap, 8, 8, true);
    int red = 0, green = 0, blue = 0, c = 0;
    int r, g, b;
    for (int y = 0; y < newBitmap.getHeight(); y++) {
        for (int x = 0; x < newBitmap.getHeight(); x++) {
            int color = newBitmap.getPixel(x, y);
            r = (color >> 16) & 0xFF;
            g = (color >> 8) & 0xFF;
            b = color & 0xFF;
            if (r > 200 || g > 200 || b > 200) {
                continue;
            }
            red += r;
            green += g;
            blue += b;
            c++;
        }
    }
    newBitmap.recycle();
    red = Math.max(0, Math.min(0xFF, red / c));
    green = Math.max(0, Math.min(0xFF, green / c));
    blue = Math.max(0, Math.min(0xFF, blue / c));
    return (0xFF << 24) | (red << 16) | (green << 8) | blue;
}

See More Examples