图片缩小后加入内存

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.widget.ImageView;

public class DemoActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ImageView iv = (ImageView) this.findViewById(R.id.iv);
//        BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
//        //按1/8的大小加载到内存 
//        bmpFactoryOptions.inSampleSize = 8;
//        Bitmap bm = BitmapFactory.decodeFile("/sdcard/img.jpg",bmpFactoryOptions);
//        iv.setImageBitmap(bm);
        //1. 首先得到屏幕的宽高
        Display currentDisplay = getWindowManager().getDefaultDisplay();
        int dw = currentDisplay.getWidth();
        int dh = currentDisplay.getHeight();
        // 2. 获取图片的宽度和高度 
        BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
        // 设置inJustDecodeBounds = true ;
        bmpFactoryOptions.inJustDecodeBounds = true;
        // 不会真正的解析这个位图 
        Bitmap bmp = BitmapFactory.decodeFile("/sdcard/img.jpg", bmpFactoryOptions);
        //得到图片的宽度和高度 
        int heightRatio = (int)Math.ceil(bmpFactoryOptions.outHeight/(float)dh);
        int widthRatio = (int)Math.ceil(bmpFactoryOptions.outWidth/(float)dw);
        
        //真正的解析位图 
        bmpFactoryOptions.inJustDecodeBounds = false;
   
        if(heightRatio>widthRatio){
            bmpFactoryOptions.inSampleSize = heightRatio;
        }else{
         bmpFactoryOptions.inSampleSize = widthRatio;
        }
        bmp = BitmapFactory.decodeFile("/sdcard/img.jpg", bmpFactoryOptions);
        
        iv.setImageBitmap(bmp);
    }
}

你可能感兴趣的:(bitmap,imageview)