public class MainActivity extends AppCompatActivity { ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageView = findViewById(R.id.imageView); Bitmap bm = decodeBitmapFromResource(); imageView.setImageBitmap(bm); } public Bitmap decodeBitmapFromResource(){ //Options 是选项的意思 BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(getResources(),R.mipmap.aa,options); options.inSampleSize = caculateSimpleSize(options,200,200); options.inJustDecodeBounds = false; return BitmapFactory.decodeResource(getResources(),R.mipmap.aa,options); } //这个方法是用来计算合适的采样率 public int caculateSimpleSize(BitmapFactory.Options options ,int reqWidth,int reqHeight){ int width = options.outWidth; int height = options.outHeight; //采样率为1 int inSampleSize = 1; int halfWidth = width/2; int halfHeight = height/2; //当我们所需的宽度(reqWidth)和高度(reqHeight)比你的图片等比压缩小时我们就停止压缩 while ((halfHeight/inSampleSize) > reqWidth &&(halfHeight/inSampleSize)>reqHeight){ inSampleSize *= 2; } return inSampleSize; } }
Bitmap压缩图片
最新推荐文章于 2023-03-29 15:15:52 发布