We can generate a shrinked bitmap using BitmapFactory.Options with inSampleSize; such that to reduce the needed resources greatly.
package com.AndroidLoadImageView;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;
public class AndroidLoadImageViewActivity extends Activity {
String imagefile ="/sdcard/IMG_9331.JPG";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView image = (ImageView)findViewById(R.id.image);
//Bitmap bm = BitmapFactory.decodeFile(imagefile);
Bitmap bm = ShrinkBitmap(imagefile, 300, 300);
image.setImageBitmap(bm);
}
Bitmap ShrinkBitmap(String file, int width, int height){
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions);
int heightRatio = (int)Math.ceil(bmpFactoryOptions.outHeight/(float)height);
int widthRatio = (int)Math.ceil(bmpFactoryOptions.outWidth/(float)width);
if (heightRatio > 1 || widthRatio > 1)
{
if (heightRatio > widthRatio)
{
bmpFactoryOptions.inSampleSize = heightRatio;
} else {
bmpFactoryOptions.inSampleSize = widthRatio;
}
}
bmpFactoryOptions.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions);
return bitmap;
}
}
next post:
- Ready image file using build-in Gallery, with Intent.ACTION_PICK
How do I use above for following?
ReplyDeleteBitmap b = BitmapFactory.decodeStream(inputStream);
?
hello Ashok,
ReplyDeleteplease read: Ready image file using build-in Gallery, with Intent.ACTION_PICK
Thank you, but this algorithm produces inSampleSize values too small to be useable, my image requires a minimum (and thus ideal) value of 2 and yet it receives a 7 from this, making it insanely small.
ReplyDeleteSorry, I meant values too big.
ReplyDeleteNot working.
ReplyDeleteNull pointer Exception at image.setImageBitmap(bm);
How can i save this image again in my path ..by replacing the same one..
ReplyDeletePlease read Save the captured canvas bitmap from custom View. You can find image saving code in openCaptureDialog().
DeleteThis is the code written by Chris Haseman in the book "Creating Android Applications Develop and Design"... You copier
ReplyDeleteAre you talking about this book published at December 25, 2011?
DeletePlease understand that it's a very common approach, you can find many similary code in internet, include Google Developers Website.
Thank you for this, I followed your tutorial, works fine, please help me with: http://stackoverflow.com/questions/16954109/reduce-the-size-of-a-bitmap-to-a-specified-size-in-android?noredirect=1#comment24483212_16954109
ReplyDelete