How to subsample/resize an image like in whatsapp

风格不统一 提交于 2019-11-30 16:43:44

You can checkout this code it works same as you wanted WhatsApp Like Image Compression. This code has been modified according to my usage. Using this code will provide you :

  • Low Size Images around 100kb without playing with image quality.
  • High pixel images will be scaled down to maxWidth and maxHeight without loosing its original quality.

Original Article : Loading images Super-Fast like WhatsApp

Demo :

Original Image : Size - 3.84Mb Dimensions - 3120*4160

Compressed Image : Size - 157Kb Dimensions - 960*1280

Edit 1: You can also make a custom Square ImageView which extends ImageView Class. SquareImageView

How to subsample/resize an image like in whatsapp

  • You can do it by simply using Glide as follows. Replace the value 500,500 with your required image quality.

    Glide.with(getApplicationContext())
                .load(uri)
                .asBitmap()
                .into(new SimpleTarget<Bitmap>(500, 500) {
                    @Override
                    public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
                        bitmap = resource;//this is the required bitmap
                        imageView.setImageBitmap(resource); 
                    }
                });
    
  • If you want to save the Bitmap as a file, use the following method

      private File savebitmap(String filename) {
      String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
      OutputStream outStream = null;
    
      File file = new File(filename + ".png");
      if (file.exists()) {
         file.delete();
         file = new File(extStorageDirectory, filename + ".png");
         Log.e("file exist", "" + file + ",Bitmap= " + filename);
      }
      try {
         // make a new bitmap from your file
         Bitmap bitmap = BitmapFactory.decodeFile(file.getName());
    
         outStream = new FileOutputStream(file);
         bitmap.compress(Bitmap.CompressFormat.JPG, 100, outStream);
         outStream.flush();
         outStream.close();
      } catch (Exception e) {
         e.printStackTrace();
      }
      Log.e("file", "" + file);
      return file;
    

    }

  • To include Glide in your project, add the following to your gradle file

     repositories {
     mavenCentral() // jcenter() works as well because it pulls from Maven    Central
     }
    
     dependencies {
     compile 'com.github.bumptech.glide:glide:3.7.0'
     compile 'com.android.support:support-v4:19.1.0'
     }
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!