public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView img1=findViewById(R.id.img1);
ImageView img2=findViewById(R.id.img2);
LruCache<String,Bitmap> cache;
//图片的sd的路径
String picPath = Environment.getExternalStorageDirectory().getPath() + File.separator + "bb.JPG";
Bitmap bitmap = BitmapFactory.decodeFile(picPath);
img1.setImageBitmap(bitmap);
Bitmap compressPic = getCompressPic(picPath, 120, 120);
img2.setImageBitmap(compressPic);
}
/**
* 二次采样
* @param picPath 图片的路径
* @param expectWidth 期望的图片的宽度 (px)
* @param expectHeight 期望的图片的高度 (px)
* @return
*/
public Bitmap getCompressPic(String picPath,int expectWidth,int expectHeight){
//第一次采样:得到图片的实际的宽度与高度
BitmapFactory.Options options=new BitmapFactory.Options();
options.inJustDecodeBounds=true;//必须设置成true
//转换
BitmapFactory.decodeFile(picPath,options);
//得到图片的实际宽度与高度
int realWidth = options.outWidth;
int realHeight = options.outHeight;
Log.d("zzz","实际的宽度:"+realWidth+" 实际的高度:"+realHeight);
/第一次采样end///
//第二次采样:计算一个压缩值
int sampleSize=1;
if(realHeight>expectHeight || realWidth>expectWidth){
int heightRate = realHeight / expectHeight;
int widthRate = realWidth / expectWidth;
//计算值 3
sampleSize=heightRate>widthRate?heightRate:widthRate;
Log.d("zzz","sampleSize:"+sampleSize);
}
options.inJustDecodeBounds=false;//第二次采样时设置成false
options.inSampleSize=sampleSize;//压缩率
options.inPreferredConfig= Bitmap.Config.RGB_565;//设置图片的色彩模式 1px=2个字节
//压缩后的图片
Bitmap bitmap = BitmapFactory.decodeFile(picPath, options);
/第二次采样end///
return bitmap;
}
}