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:org.appcelerator.titanium.view.TiDrawableReference.java

/**
 * Gets the bitmap, scaled to a width & height specified in TiDimension params.
 * @param destWidthDimension (null-ok) TiDimension specifying the desired width.  If .isUnitAuto()
 * then the width will be the source width.  If destWidthDimension is null, then the TiContext
 * will be used to determine the activity window's decor width and use that.
 * @param destHeightDimension (null-ok) TiDimension specifying the desired height.  If .isUnitAuto()
 * then the height will be the source height.  If destHeightDimension is null, then resulting height will
 * be at same ratio to the resulting width as the original height:width.
 * @return Bitmap, or null if any problem getting it.  Check logcat if null.
 *///from  w  w w  .  j av a 2s  .com
public Bitmap getBitmap(View parent, TiDimension destWidthDimension, TiDimension destHeightDimension) {
    int srcWidth, srcHeight, destWidth, destHeight;

    Bounds bounds = peekBounds();
    srcWidth = bounds.width;
    srcHeight = bounds.height;

    if (srcWidth <= 0 || srcHeight <= 0) {
        Log.w(TAG, "Bitmap bounds could not be determined. If bitmap is loaded, it won't be scaled.");
        return getBitmap(); // fallback
    }

    if (parent == null) {
        Activity activity = softActivity.get();
        if (activity != null && activity.getWindow() != null) {
            parent = activity.getWindow().getDecorView();
        }
    }

    Bounds destBounds = calcDestSize(srcWidth, srcHeight, destWidthDimension, destHeightDimension, parent);
    destWidth = destBounds.width;
    destHeight = destBounds.height;

    // If src and dest width/height are same, no need to go through all the sampling and scaling jazz.
    if (srcWidth == destWidth && srcHeight == destHeight) {
        return getBitmap();
    }

    if (destWidth <= 0 || destHeight <= 0) {
        // calcDestSize() should actually prevent this from happening, but just in case...
        Log.w(TAG, "Bitmap final bounds could not be determined.  If bitmap is loaded, it won't be scaled.");
        return getBitmap();
    }

    InputStream is = getInputStream();
    if (is == null) {
        Log.w(TAG, "Could not open stream to get bitmap");
        return null;
    }

    Bitmap b = null;
    try {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inInputShareable = true;
        opts.inPurgeable = true;
        opts.inSampleSize = calcSampleSize(srcWidth, srcHeight, destWidth, destHeight);
        if (Log.isDebugModeEnabled()) {
            StringBuilder sb = new StringBuilder();
            sb.append("Bitmap calcSampleSize results: inSampleSize=");
            sb.append(opts.inSampleSize);
            sb.append("; srcWidth=");
            sb.append(srcWidth);
            sb.append("; srcHeight=");
            sb.append(srcHeight);
            sb.append("; finalWidth=");
            sb.append(opts.outWidth);
            sb.append("; finalHeight=");
            sb.append(opts.outHeight);
            Log.d(TAG, sb.toString());
        }

        Bitmap bTemp = null;
        try {
            oomOccurred = false;
            bTemp = BitmapFactory.decodeStream(is, null, opts);
            if (bTemp == null) {
                Log.w(TAG, "Decoded bitmap is null");
                return null;
            }

            if (Log.isDebugModeEnabled()) {
                StringBuilder sb = new StringBuilder();
                sb.append("decodeStream resulting bitmap: .getWidth()=" + bTemp.getWidth());
                sb.append("; .getHeight()=" + bTemp.getHeight());
                sb.append("; getDensity()=" + bTemp.getDensity());
                Log.d(TAG, sb.toString());
            }

            // Set the bitmap density to match the view density before scaling, so that scaling
            // algorithm takes destination density into account.
            DisplayMetrics displayMetrics = new DisplayMetrics();
            displayMetrics.setToDefaults();
            bTemp.setDensity(displayMetrics.densityDpi);

            // Orient the image when orientation is set.
            if (autoRotate) {
                // Only set the orientation if it is uninitialized
                if (orientation < 0) {
                    orientation = getOrientation();
                }
                if (orientation > 0) {
                    return getRotatedBitmap(bTemp, orientation);
                }
            }

            if (bTemp.getNinePatchChunk() != null) {
                // Don't scale nine-patches
                b = bTemp;
                bTemp = null;
            } else {
                Log.d(TAG, "Scaling bitmap to " + destWidth + "x" + destHeight, Log.DEBUG_MODE);

                // If anyDensity=false, meaning Android is automatically scaling
                // pixel dimensions, need to do that here as well, because Bitmap width/height
                // calculations do _not_ do that automatically.
                if (anyDensityFalse && displayMetrics.density != 1f) {
                    destWidth = (int) (destWidth * displayMetrics.density + 0.5f); // 0.5 is to force round up of dimension. Casting to int drops decimals.
                    destHeight = (int) (destHeight * displayMetrics.density + 0.5f);
                }

                // Created a scaled copy of the bitmap. Note we will get
                // back the same bitmap if no scaling is required.
                b = Bitmap.createScaledBitmap(bTemp, destWidth, destHeight, true);
            }

        } catch (OutOfMemoryError e) {
            oomOccurred = true;
            Log.e(TAG, "Unable to load bitmap. Not enough memory: " + e.getMessage(), e);

        } finally {
            // Recycle the temporary bitmap only if it isn't
            // the same instance as our scaled bitmap.
            if (bTemp != null && bTemp != b) {
                bTemp.recycle();
                bTemp = null;
            }
        }

    } finally {
        try {
            is.close();
        } catch (IOException e) {
            Log.e(TAG, "Problem closing stream: " + e.getMessage(), e);
        }
    }
    if (Log.isDebugModeEnabled()) {
        StringBuilder sb = new StringBuilder();
        sb.append("Details of returned bitmap: .getWidth()=" + b.getWidth());
        sb.append("; getHeight()=" + b.getHeight());
        sb.append("; getDensity()=" + b.getDensity());
        Log.d(TAG, sb.toString());
    }
    return b;
}

From source file:com.android.leanlauncher.IconCache.java

public Bitmap createIconBitmapFromTheme(String iconDrawableName, Drawable defaultDrawable) {
    Bitmap icon = loadBitmapFromIconPack(iconDrawableName);

    if (icon == null) {
        Log.d(TAG, "Using default icon, can't find icon drawable: " + iconDrawableName + " in "
                + mCurrentIconTheme);//from w  w  w.ja  v  a  2s  . com
        icon = ((BitmapDrawable) defaultDrawable).getBitmap();
    }

    if (mIconBackgrounds.size() < 1) {
        // we are done
        return icon;
    } else {
        Random r = new Random();
        int backImageInd = r.nextInt(mIconBackgrounds.size());
        Bitmap background = mIconBackgrounds.get(backImageInd);
        if (background == null) {
            Log.d(TAG, "Can't load background image: " + mIconBackgrounds.get(backImageInd));
            return icon;
        }

        int w = background.getWidth(), h = background.getHeight();
        Bitmap result = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        final Canvas tempCanvas = new Canvas(result);

        // draw the background first
        tempCanvas.drawBitmap(background, 0, 0, null);

        // create a mutable mask bitmap with the same mask
        if (icon.getWidth() > w || icon.getHeight() > h) {
            mIconScaleFactor = (mIconScaleFactor == 0) ? 1 : mIconScaleFactor;
            icon = Bitmap.createScaledBitmap(icon, (int) (w * mIconScaleFactor), (int) (h * mIconScaleFactor),
                    false);
        }

        if (mIconMask != null) {
            renderIconBackground(icon, mIconMask, tempCanvas, w, h, true);
        } else {
            renderIconBackground(icon, background, tempCanvas, w, h, false);
        }

        // paint the front
        if (mIconFront != null) {
            tempCanvas.drawBitmap(mIconFront, 0, 0, null);
        }

        return result;
    }
}

From source file:edu.sfsu.csc780.chathub.ui.activities.MainActivity.java

private Bitmap scaleImage(Bitmap bitmap) {
    int originalHeight = bitmap.getHeight();
    int originalWidth = bitmap.getWidth();
    double scaleFactor = MAX_LINEAR_DIMENSION / (double) (originalHeight + originalWidth);

    // We only want to scale down images, not scale upwards
    if (scaleFactor < 1.0) {
        int targetWidth = (int) Math.round(originalWidth * scaleFactor);
        int targetHeight = (int) Math.round(originalHeight * scaleFactor);
        return Bitmap.createScaledBitmap(bitmap, targetWidth, targetHeight, true);
    } else {//  w  w w.jav  a  2  s. c  om
        return bitmap;
    }
}

From source file:com.abc.driver.TruckActivity.java

private void doCrop() {
    Log.d(TAG, "doCrop()");
    final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();

    Intent intent = new Intent("com.android.camera.action.CROP");
    intent.setType("image/*");

    List<ResolveInfo> list = this.getPackageManager().queryIntentActivities(intent, 0);

    int size = list.size();

    if (size == 0) {
        Log.d(TAG, " Crop activity is not found.  List size is zero.");
        Bitmap tmpBmp = BitmapFactory.decodeFile(imageUri.getPath(), null);
        trcukLicenseBmp = Bitmap.createScaledBitmap(tmpBmp, IMAGE_WIDTH, IMAGE_HEIGHT, false);

        mTLPiv.setImageBitmap(trcukLicenseBmp);
        isPortraitChanged = true;/*ww w  . j  a  v a 2s .c  om*/

        Log.d(TAG, "set bitmap");

        return;
    } else {
        Log.d(TAG, "found the crop activity.");
        intent.setData(imageUri);

        intent.putExtra("outputX", IMAGE_WIDTH);
        intent.putExtra("outputY", IMAGE_HEIGHT);
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", true);

        if (size == 1) {
            Log.d(TAG, "Just one as choose it as crop activity.");
            Intent i = new Intent(intent);
            ResolveInfo res = list.get(0);
            i.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));

            startActivityForResult(i, CellSiteConstants.CROP_PICTURE);
        } else {
            Log.d(TAG, "More that one activity for crop  is found . will chooose one");
            for (ResolveInfo res : list) {
                final CropOption co = new CropOption();

                co.title = getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
                co.icon = getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);
                co.appIntent = new Intent(intent);

                co.appIntent
                        .setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));

                cropOptions.add(co);
            }

            CropOptionAdapter adapter = new CropOptionAdapter(getApplicationContext(), cropOptions);

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Choose Crop App");

            builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int item) {
                    startActivityForResult(cropOptions.get(item).appIntent, CellSiteConstants.CROP_PICTURE);
                }
            });

            builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
                // @Override
                public void onCancel(DialogInterface dialog) {
                    if (imageUri != null) {
                        getContentResolver().delete(imageUri, null, null);
                        imageUri = null;
                        isPortraitChanged = false;
                    }
                }
            });
            AlertDialog alert = builder.create();

            alert.show();
        }
    }
}

From source file:com.raspi.chatapp.ui.chatting.SendImageFragment.java

/**
 * saves a copy in the internal storage. This may be used for displaying when
 * rendering the real image in background. As this is image is really low
 * quality it is loaded instantly (size is a couple bytes) you can load
 * this in the main thread while the background thread will do the heavy
 * loading task./*from w w w  . ja  v  a  2 s  .  c  o m*/
 *
 * @param context      the context used to get the localStorage
 * @param fileLocation the location of the file that is to be saved
 * @param id           the messageId of the imageMessage, for the file name
 * @param chatId       the chatId of the chat the image is from, for the file name
 */
private void saveImageCopy(Context context, String fileLocation, Long id, String chatId) {
    try {
        //old images bitmap
        Bitmap oldImg = BitmapFactory.decodeFile(fileLocation);
        // sample the height to 50 and maintain the aspect ratio
        float height = 50;
        float x = oldImg.getHeight() / height;
        float width = oldImg.getWidth() / x;

        // generate the destination file
        File destFile = new File(context.getFilesDir(), chatId + "-" + id + ".jpg");
        OutputStream out = new FileOutputStream(destFile);
        // generate the bitmap to compress to file
        Bitmap image = Bitmap.createScaledBitmap(oldImg, (int) width, (int) height, true);
        // compress the bitmap to file
        image.compress(Bitmap.CompressFormat.JPEG, 20, out);
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.tealeaf.TeaLeaf.java

private Bitmap rotateBitmap(Bitmap bitmap, int rotate) {
    // rotate as needed
    Bitmap bmp;/*from   w  w w . j  a va  2  s  .co m*/

    //only allow the largest size to be 768 for now, several phones
    //including the galaxy s3 seem to crash with rotating very large 
    //images (out of memory errors) from the gallery
    int w = bitmap.getWidth();
    int h = bitmap.getHeight();
    Bitmap scaled = bitmap;
    if (w > h && w > 768) {
        float ratio = 768.f / (float) w;
        w = 768;
        h = (int) (ratio * h);
        scaled = Bitmap.createScaledBitmap(bitmap, w, h, true);
        if (bitmap != scaled) {
            bitmap.recycle();
        }
    }
    if (h > w && h > 768) {
        float ratio = 768.f / (float) h;
        h = 768;
        w = (int) (ratio * w);
        scaled = Bitmap.createScaledBitmap(bitmap, w, h, true);
        if (bitmap != scaled) {
            bitmap.recycle();
        }
    }

    int newWidth = scaled.getWidth();
    int newHeight = scaled.getHeight();

    int degrees = 0;
    if (rotate == ROTATE_90 || rotate == ROTATE_270) {
        newWidth = scaled.getHeight();
        newHeight = scaled.getWidth();
    }

    Matrix matrix = new Matrix();
    matrix.postRotate(rotate);

    bmp = Bitmap.createBitmap(scaled, 0, 0, scaled.getWidth(), scaled.getHeight(), matrix, true);
    if (scaled != bmp) {
        scaled.recycle();
    }

    return bmp;
}

From source file:com.pongme.utils.ImageDownloader.java

/**
 * Resize the bitmap to save Memory when put in cache
 * //from w  ww  .  j a  v a 2 s.c  o m
 * @param bitmap
 *            based big downloaded bitmap
 * @param imageTempWidth
 *            new Width in pixels
 * @param imageTempHeight
 *            new Height in pixels
 * @return the new resized image
 */
private Bitmap resizeToFit(Bitmap bitmap, int imageTempWidth, int imageTempHeight) {
    if (bitmap == null) {
        return null;
    }

    if (imageTempWidth > 0 && imageTempHeight > 0 && bitmap.getWidth() > 0 && bitmap.getHeight() > 0) {
        float deltaX = ((float) imageTempWidth) / ((float) bitmap.getWidth());
        float deltaY = ((float) imageTempHeight) / ((float) bitmap.getHeight());
        float delta = Math.max(deltaX, deltaY);

        if (delta < 1) {
            bitmap = Bitmap.createScaledBitmap(bitmap, (int) (delta * bitmap.getWidth()),
                    (int) (delta * bitmap.getHeight()), false);

            // Bitmap bitmap2 = ImageUtils.resizeBitmap(bitmap, delta);
            // bitmap = bitmap2;
        }
    }

    return bitmap;
}

From source file:com.MustacheMonitor.MustacheMonitor.StacheCam.java

/**
 * Return a scaled bitmap based on the target width and height
 *
 * @param imagePath//from w  w  w . j av  a  2 s. c  om
 * @return
 */
private Bitmap getScaledBitmap(String imagePath) {
    // If no new width or height were specified return the original bitmap
    if (this.targetWidth <= 0 && this.targetHeight <= 0) {
        return BitmapFactory.decodeFile(imagePath);
    }

    // figure out the original width and height of the image
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(imagePath, options);

    // 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 = BitmapFactory.decodeFile(imagePath, options);

    return Bitmap.createScaledBitmap(unscaledBitmap, widthHeight[0], widthHeight[1], true);
}

From source file:justforcommunity.radiocom.activities.Home.java

public void setTransmissionDTO(LiveBroadcastDTO liveBroadcastDTO) {
    audioIntent = new Intent(Home.this, StreamingService.class);
    audioIntent.putExtra("audio", station.getStream_url());
    audioIntent.putExtra("title", station.getStation_name());
    audioIntent.putExtra("text", getCityByCoords(station.getLatitude(), station.getLongitude()));

    // Get name of program
    if (liveBroadcastDTO != null && !liveBroadcastDTO.getName().isEmpty()) {
        audioIntent.putExtra("text", liveBroadcastDTO.getName());
    }/*from  www .  j  av  a2 s .c o  m*/

    // Get logo of program
    if (liveBroadcastDTO != null && liveBroadcastDTO.getLogo_url() != null) {
        Picasso.with(this).load(liveBroadcastDTO.getLogo_url()).into(new Target() {
            @Override
            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                bitmap = Bitmap.createScaledBitmap(bitmap, 300, 300, true);
                // bitmap = Bitmap.createBitmap(bitmap, 0, 0, 300, 300);
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
                audioIntent.putExtra("logo", stream.toByteArray());
                startService(audioIntent);
            }

            @Override
            public void onBitmapFailed(Drawable errorDrawable) {
                startService(audioIntent);
            }

            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable) {
            }
        });
    } else {
        startService(audioIntent);
    }

    navigationView.getMenu().getItem(2).setTitle(getResources().getString(R.string.drawer_item_streaming_stop));
    navigationView.getMenu().getItem(2).setIcon(R.drawable.streamingstop);
    fab_media.setImageResource(R.drawable.streamingstopwhite);
    playing = true;
    edit.putBoolean("isMediaPlaying", playing);
    edit.commit();
}