Showing posts with label scale down the image in android. Show all posts
Showing posts with label scale down the image in android. Show all posts

Sunday, 23 September 2012

bitmap - How to scale down the image for better quality on Android

Hello Friends,

How to scale down the image with better quality , without affecting the image 
Aspect Ration ?

I am sharing my android | java code with the help of which we can easily scale down
the image .

Note: Here in my function i am passing two parameter one is imageview and the other is 
         integer variable which is in dp(eg: int boundBoxInDp = 50 ).

  * Scaling down the image
 public Bitmap getScaleImage(ImageView view, int boundBoxInDp) {
  Drawable drawing = view.getDrawable();
  Bitmap bitmap = ((BitmapDrawable) drawing).getBitmap();

  // Get current dimensions
  int width = bitmap.getWidth();
  int height = bitmap.getHeight();

  // Determine how much to scale: the dimension requiring
                // less scaling is.
  // closer to the its side. This way the image always 
                // stays inside your.
  // bounding box AND either x/y axis touches it.
  float xScale = ((float) boundBoxInDp) / width;
  float yScale = ((float) boundBoxInDp) / height;
  float scale = (xScale <= yScale) ? xScale : yScale;

  // Create a matrix for the scaling and add the scaling data
  Matrix matrix = new Matrix();
  matrix.postScale(scale, scale);

  // Create a new bitmap and convert it to a format understood
                // by the
  // ImageView
  Bitmap scaledBitmap = Bitmap.
                     createBitmap(bitmap, 0, 0, width, height,
                     matrix, true);
  // Apply the scaled bitmap
  return scaledBitmap;


Hope , this will helps some one.
Enjoy coding........ :)


Copyright @ 2013 Android Developers Blog.