Skip to content Skip to sidebar Skip to footer

Resize Bitmap Without Creating New Bitmap

Is there anyway to resize/scale bitmap without creating a new bitmap? Let say i download image that height or width is larger than 2048px. Before i can display it, i have to resize

Solution 1:

use sampling if you facing out of memory issue.

publicstaticintcalculateInSampleSize(
 BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of imagefinalintheight= options.outHeight;
finalintwidth= options.outWidth;
intinSampleSize=1;

if (height > reqHeight || width > reqWidth) {

    // Calculate ratios of height and width to requested height and widthfinalintheightRatio= Math.round((float) height / (float) reqHeight);
    finalintwidthRatio= Math.round((float) width / (float) reqWidth);

    // Choose the smallest ratio as inSampleSize value, this will guarantee// a final image with both dimensions larger than or equal to the// requested height and width.
    inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}

return inSampleSize;
}

publicstatic Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
    int reqWidth, int reqHeight) {

// First decode with inJustDecodeBounds=true to check dimensionsfinal BitmapFactory.Optionsoptions=newBitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);

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

// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}

At the end for setting image in Imageview, use this

mImageView.setImageBitmap(decodeSampledBitmapFromResource(getResources(),R.id.myimage,    
Screen_width, screen_height));

Must read this

Post a Comment for "Resize Bitmap Without Creating New Bitmap"