码迷,mamicode.com
首页 > 其他好文 > 详细

把大图片加载进内存

时间:2016-03-31 12:51:50      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:

把图片加载进内存,要对图片进行缩放,否则内存溢出

代码:

 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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!