标签:
把图片加载进内存,要对图片进行缩放,否则内存溢出
代码:
1 package com.example.loadimage; 2 3 import android.os.Bundle; 4 import android.app.Activity; 5 import android.graphics.Bitmap; 6 import android.graphics.BitmapFactory; 7 import android.graphics.BitmapFactory.Options; 8 import android.graphics.Point; 9 import android.view.Menu; 10 import android.view.View; 11 import android.view.WindowManager; 12 import android.widget.ImageView; 13 14 public class MainActivity extends Activity { 15 16 private int windowHeight; 17 private int windowWidth; 18 private ImageView iv; 19 @Override 20 protected void onCreate(Bundle savedInstanceState) { 21 super.onCreate(savedInstanceState); 22 setContentView(R.layout.activity_main); 23 iv = (ImageView) findViewById(R.id.iv); 24 25 WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE); 26 windowHeight = wm.getDefaultDisplay().getHeight(); 27 windowWidth = wm.getDefaultDisplay().getWidth(); 28 29 //3.0以后版本的使用方法 30 /* Point outSize = new Point(); 31 wm.getDefaultDisplay().getSize(outSize); 32 windowWidth = outSize.x; 33 windowHeight = outSize.y;*/ 34 35 } 36 37 public void load(View view){ 38 //下面两行注释代码,如果图片过大,则内存会溢出 39 //Bitmap bitmap = BitmapFactory.decodeFile("/sdcard/33.jpg"); 40 //iv.setImageBitmap(bitmap); 41 //图片解析配置 42 BitmapFactory.Options opts = new Options(); 43 //这个设置是为了不去解析图片,即不把图片加进内存中,而是返回图片的头部信息 44 opts.inJustDecodeBounds = true; 45 BitmapFactory.decodeFile("/sdcard/aa.jpg", opts); 46 //图片的真实高度和宽度 47 int imageWidth = opts.outWidth; 48 int imageHeight = opts.outHeight; 49 System.out.println("宽为:" + imageWidth); 50 System.out.println("高为:" + imageHeight); 51 52 //计算缩放比例 53 int scaleX = imageWidth / windowWidth; 54 int scaleY = imageHeight / windowHeight; 55 int scale = 1; 56 if(scaleX > scaleY & scaleY >= 1){ 57 scale = scaleX; 58 } 59 60 if(scaleY > scaleX & scaleX >= 1){ 61 scale = scaleY; 62 } 63 //真的去解析图片 64 opts.inJustDecodeBounds = false; 65 66 //采样率 67 opts.inSampleSize = scale; 68 Bitmap bitmap = BitmapFactory.decodeFile("/sdcard/aa.jpg", opts); 69 iv.setImageBitmap(bitmap); 70 } 71 72 }
标签:
原文地址:http://www.cnblogs.com/zhongyinghe/p/5340390.html