Wednesday, June 25, 2014

How to compress image for imageview in android


   Below logic is used for compress the image before assign to image-view in android application.
             
                 File image = new  File("/storage/sdcard0/DCIM/Camera/1403687038055.jpg");

Bitmap bitmap = decodeSampledBitmapFromFile(image.getAbsolutePath(), 1000, 700);

ImageView imag=(ImageView)findViewById(R.id.imageView1);
imag.setImageBitmap(bitmap);



        public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight)
{ // BEST QUALITY MATCH
   
   //First decode with inJustDecodeBounds=true to check dimensions
   final BitmapFactory.Options options = new BitmapFactory.Options();
   options.inJustDecodeBounds = true;
   BitmapFactory.decodeFile(path, options);

   // Calculate inSampleSize, Raw height and width of image
   final int height = options.outHeight;
   final int width = options.outWidth;
   options.inPreferredConfig = Bitmap.Config.RGB_565;
   int inSampleSize = 1;

   if (height > reqHeight)
   {
       inSampleSize = Math.round((float)height / (float)reqHeight);
   }
   int expectedWidth = width / inSampleSize;

   if (expectedWidth > reqWidth)
   {
       //if(Math.round((float)width / (float)reqWidth) > inSampleSize) // If bigger SampSize..
       inSampleSize = Math.round((float)width / (float)reqWidth);
   }

   options.inSampleSize = inSampleSize;

   // Decode bitmap with inSampleSize set
   options.inJustDecodeBounds = false;


   return BitmapFactory.decodeFile(path, options);
}

No comments:

Post a Comment