先得到位图宽高不用加载位图,然后按ImageView比例缩放,得到缩放的尺寸进行压缩并加载位图.inSampleSize是缩放多少倍,小于1默认是1,通过调节其inSampleSize参数,比如调节为2,宽高会为原来的1/2,内存变回原来的1/4.
布局文件
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\_main);
ImageView imageView = findViewById(R.id.image);
BitmapFactory.Options factoryOptions = new BitmapFactory.Options();
// 不将图片读取到内存中,仍然可以通过参数获得它的高宽
factoryOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile("/sdcard/AAAImage/image2.png", factoryOptions);
int imageWidth = factoryOptions.outWidth;
int imageHeight = factoryOptions.outHeight;
ViewGroup.LayoutParams layoutParams = imageView.getLayoutParams();
int width2 = layoutParams.width;
int height2 = layoutParams.height;
// 等比缩小,previewWidth和height是imageView的宽高
int scaleFactor = Math.max(imageWidth /width2,
imageHeight /height2);
// 将图片读取到内存中
factoryOptions.inJustDecodeBounds = false;
// 设置等比缩小图
factoryOptions.inSampleSize = scaleFactor;
// 样图可以回收内存
factoryOptions.inPurgeable = true;
Bitmap uploadImage = BitmapFactory
.decodeFile("/sdcard/AAAImage/image2.png", factoryOptions);
imageView.setImageBitmap(uploadImage);
//加载显示一符图像,对内存的使用有显著影响,BitmapFactory提供了一系列静态方法加载不同来源的图片。
}
}
位图缩放可以优化内存,面试必考
手机扫一扫
移动阅读更方便
你可能感兴趣的文章