How To Scaling Bitmap To Screen Density in Android

Sometimes when loading an image that you are working with limited memory, ideally you only want to load a lower resolution drawable image in memory. The lower resolution of image should match the size of the screen displays it. An image with a higher resolution does not provide any visible benefit, but still takes up precious memory and incurs additional performance overhead due to additional on the fly scaling.

Now i will share how to scaling image with any kind size to without losing quality of the bitmap image , Hope will save your time for code .

Scalling Bitmap Codes for Java Android

Add code bellow inside your class

   public void loadBitmap(int resId, ImageView imageView) {  
        final String imageKey = String.valueOf(resId);  
        final Bitmap bitmap = getBitmapFromMemCache(imageKey);  
        if (bitmap != null) {  
            imageView.setImageBitmap(bitmap);  
        } else {  
            imageView.setImageResource(R.drawable.ic_launcher);  
            BitmapWorkerTask task = new BitmapWorkerTask(imageView);  
            task.execute(resId);  
       }  
   }  
   static class AsyncDrawable extends BitmapDrawable {  
           private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;  
           public AsyncDrawable(Resources res, Bitmap bitmap,  
                     BitmapWorkerTask bitmapWorkerTask) {  
                super(res, bitmap);  
                bitmapWorkerTaskReference = new WeakReference<BitmapWorkerTask>(  
                          bitmapWorkerTask);  
           }  
           public BitmapWorkerTask getBitmapWorkerTask() {  
                return bitmapWorkerTaskReference.get();  
           }  
      }  
      public static boolean cancelPotentialWork(int data, ImageView imageView) {  
           final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);  
           if (bitmapWorkerTask != null) {  
                final int bitmapData = bitmapWorkerTask.data;  
                if (bitmapData != data) {  
                     // Cancel previous task  
                     bitmapWorkerTask.cancel(true);  
                } else {  
                     // The same work is already in progress  
                     return false;  
                }  
           }  
           // No task associated with the ImageView, or an existing task was  
           // cancelled  
           return true;  
      }  
      private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {  
           if (imageView != null) {  
                final Drawable drawable = imageView.getDrawable();  
                if (drawable instanceof AsyncDrawable) {  
                     final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;  
                     return asyncDrawable.getBitmapWorkerTask();  
                }  
           }  
           return null;  
      }  
      public void addBitmapToMemoryCache(String key, Bitmap bitmap) {  
           if (getBitmapFromMemCache(key) == null) {  
                mMemoryCache.put(key, bitmap);  
           }  
      }  
      public Bitmap getBitmapFromMemCache(String key) {  
           return mMemoryCache.get(key);  
      }  
      class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {  
           public int data = 0;  
           private final WeakReference<ImageView> imageViewReference;  
           public BitmapWorkerTask(ImageView imageView) {  
                // Use a WeakReference to ensure the ImageView can be garbage  
                // collected  
                imageViewReference = new WeakReference<ImageView>(imageView);  
           }  
           // Decode image in background.  
           @Override  
           protected Bitmap doInBackground(Integer... params) {  
                data = params[0];  
                final Bitmap bitmap = decodeSampledBitmapFromResource(  
                          getApplicationContext().getResources(), data, 100, 100);  
                addBitmapToMemoryCache(String.valueOf(params[0]), bitmap);  
                return bitmap;  
           }  
           // Once complete, see if ImageView is still around and set bitmap.  
           @Override  
           protected void onPostExecute(Bitmap bitmap) {  
                if (imageViewReference != null && bitmap != null) {  
                     final ImageView imageView = imageViewReference.get();  
                     if (imageView != null) {  
                          imageView.setImageBitmap(bitmap);  
                     }  
                }  
           }  
      }  
      public static Bitmap decodeSampledBitmapFromResource(Resources res,  
                int resId, int reqWidth, int reqHeight) {  
           // First decode with inJustDecodeBounds=true to check dimensions  
           final BitmapFactory.Options options = new BitmapFactory.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);  
      }  
      public static int calculateInSampleSize(BitmapFactory.Options options,  
           int reqWidth, int reqHeight) {  
           // Raw height and width of image  
           final int height = options.outHeight;  
           final int width = options.outWidth;  
           int inSampleSize = 1;  
           if (height > reqHeight || width > reqWidth) {  
                // Calculate ratios of height and width to requested height and  
                // width  
                final int heightRatio = Math.round((float) height/ (float) reqHeight);  
                final int widthRatio = 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;  
      }  

And add code bellow to get screen density

 public static int getScreenDensity(Activity activity){  
           int density = 0;  
           float level = activity.getResources().getDisplayMetrics().density;  
           if(level == L_LEVEL){  
                density = 120;  
           } else if(level == M_LEVEL){  
                density = 160;  
           } else if(level == H_LEVEL){  
                density = 240;  
           } else if(level == X_LEVEL){  
                density = 320;  
           } else {  
                density = 480;  
           }  
           return density;  
      }  

This is how to use both codes

           ImageView imageView = (ImageView) findViewById(R.id.imageview);  
           imageView.setImageBitmap(decodeSampledBitmapFromResource(getApplicationContext().getResources(),  
                       R.drawable.ic_launcher, getScreenDensity(this), getScreenDensity(this)));  

Comments

Popular posts from this blog

Tutorial Integration Firebase With Admob on Android

Firebase Configuration in Android

How To Generate A Random String Alphabet And Number in Java Android