加载大图片到内存

package com.shz.loadimg;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;

public class MainActivity extends Activity {

    private ImageView img;
    private int winHeight;
    private int winWidth;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        img = (ImageView) findViewById(R.id.img);
        WindowManager manager = (WindowManager) getSystemService(WINDOW_SERVICE);
        //manager.getDefaultDisplay().getSize(outSize);
        winHeight = manager.getDefaultDisplay().getHeight();
        winWidth = manager.getDefaultDisplay().getWidth();
    }

    public void load(View view) {
        // 如果图片的高为3000像素,宽为2600像素,每个像素点占4个byte(argb:透明度和颜色值)
        // 则加载到内存的大小是(3000*2600*4)/(1024*1024) ≈ 30M。 
        // 由于Android系统分配给每个应用的堆大小为16M(小于30M),故会出现内存溢出。
        // 所以以下方法肯定不行!
        /*Bitmap bitmap = BitmapFactory.decodeFile("/storage/sdcard/1.jpg");
        img.setImageBitmap(bitmap);*/
        
        String imgPath = "/storage/sdcard/1.jpg";
        Options opts = new Options();
        // 此属性值表示不去解析加载图片到内存,只是获取图片的头部信息(宽高,备注等)
        opts.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(imgPath, opts);
        int imgHeight = opts.outHeight;
        int imgWidth = opts.outWidth;
        
        // 计算缩放比例(取x,y中的最大值)
        int scaleX = imgWidth / winWidth;
        int scaleY = imgHeight / winHeight;
        int scale = 1;
        
        if(scaleX > scaleY & scaleY >= 1)
        {
            scale = scaleX;
        }
        
        if(scaleY > scaleX & scaleX >= 1)
        {
            scale = scaleY;
        }
        
        // 现在去解析图片
        opts.inJustDecodeBounds = false;
        opts.inSampleSize = scale;
        Bitmap bm = BitmapFactory.decodeFile(imgPath, opts);
        img.setImageBitmap(bm);
    }
}
View Code
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.shz.loadimg.MainActivity"
    tools:ignore="MergeRootFrame" >

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="load"
        android:text="加载图片" />

    <ImageView
        android:id="@+id/img"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>
View Code

 

posted @ 2014-09-01 23:24  萌浩  阅读(134)  评论(0编辑  收藏  举报