zoukankan      html  css  js  c++  java
  • Android简易实战教程--第二十八话《加载大图片》

    Android系统以ARGB表示每个像素,所以每个像素占用4个字节,很容易内存溢出。假设手机内存比较小,而要去加载一张像素很高的图片的时候,就会因为内存不足导致崩溃。这种异常是无法捕获的

    内存不足并不是说图片的大小决定的,最主要的因素是像素问题。

    因此加载大图片就要设置相应的缩放比例。

    计算机把图片所有像素信息全部解析出来,保存至内存
    Android保存图片像素信息,是用ARGB保存
    手机屏幕320*480,总像素:153600
    图片宽高2400*3200,总像素7680000
    算法:得到缩放比率
    2400 / 320 = 7
    3200 / 480 = 6


    代码:

    package com.itny.loadimage;
    
    import android.os.Bundle;
    import android.app.Activity;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.graphics.BitmapFactory.Options;
    import android.graphics.Point;
    import android.view.Display;
    import android.view.Menu;
    import android.view.View;
    import android.widget.ImageView;
    
    public class MainActivity extends Activity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }
    
    
        public void click(View v){
        	//解析图片时需要使用到的参数都封装在这个对象里了
        	Options opt = new Options();
        	//不为像素申请内存,只获取图片宽高
        	opt.inJustDecodeBounds = true;
        	BitmapFactory.decodeFile("sdcard/dog.jpg", opt);
        	//拿到图片宽高
        	int imageWidth = opt.outWidth;
        	int imageHeight = opt.outHeight;
        	
        	Display dp = getWindowManager().getDefaultDisplay();
        	//拿到屏幕宽高
    		int screenWidth = dp.getWidth();
        	int screenHeight = dp.getHeight();
        	
        	//计算缩放比例
        	int scale = 1;//表示默认不缩放
        	int scaleWidth = imageWidth / screenWidth;
        	int scaleHeight = imageHeight / screenHeight;
        	//哪个缩放比例大要哪个    >=防止缩放比例是一样的程序不执行这里
        	if(scaleWidth >= scaleHeight && scaleWidth >= 1){//scaleWidth >= 1      只缩放比屏幕像素大的图片
        		scale = scaleWidth;
        	}
        	else if(scaleWidth < scaleHeight && scaleHeight >= 1){
        		scale = scaleHeight;
        	}
        	
        	//设置缩放比例
        	opt.inSampleSize = scale;
        	//这个时候有了缩放比了。因此要再一次为图片申请内存,使用BitmapFactory去解析位图
        	opt.inJustDecodeBounds = false;
        	//此时的Bitmap就是缩放后的Bitmap。
        	Bitmap bm = BitmapFactory.decodeFile("sdcard/dog.jpg", opt);
        	
        	ImageView iv = (ImageView) findViewById(R.id.iv);
        	iv.setImageBitmap(bm);//Sets a Bitmap as the content of this ImageView.
        }
        
    }
    
    这样就能加载一张较大的图片了,运行如下:


  • 相关阅读:
    怎样才能算是在技术上活跃的小公司
    jquery幻灯片--渐变
    cpm效果介绍
    我依然热爱编程
    项目开发经验终结2015/4/7
    windows上putty访问ubuntu
    ubuntu安装openssh-server
    今天犯了一个低级错误
    linux 搭建lamp环境
    能用存储过程的DBHelper类
  • 原文地址:https://www.cnblogs.com/wanghang/p/6299596.html
Copyright © 2011-2022 走看看