先得到位图宽高不用加载位图,然后按ImageView比例缩放,得到缩放的尺寸进行压缩并加载位图.inSampleSize是缩放多少倍,小于1默认是1,通过调节其inSampleSize参数,比如调节为2,宽高会为原来的1/2,内存变回原来的1/4.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:id="@+id/line1" android:layout_height="match_parent" tools:context=".MainActivity"> <ImageView android:id="@+id/image" android:layout_width="match_parent" android:layout_height="300dp" /> </LinearLayout>
布局文件
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提供了一系列静态方法加载不同来源的图片。 } }
位图缩放可以优化内存