Androidx學習筆記(72)--- 加載大圖片

多媒體編程

  • 文本、圖片、音頻、視頻

圖片

  • 圖片在計算機中的大小
  • 圖片的總大小 = 圖片的總像素 * 每個像素佔用的大小
  • 單色位圖:只能表示2種顏色
    • 使用兩個數字:0和1
    • 使用一個長度爲1的二進制數字就可以表示了
    • 每個像素佔用1/8個字節
  • 16色位圖:能表示16種顏色
    • 需要16個數字:0-15,0000 - 1111
    • 使用一個長度爲4的二進制數組就可以表示了
    • 每個像素佔用1/2個字節
  • 256色位圖:能表示256種顏色
    • 需要256個數字:0 - 255,0000 0000 - 1111 1111
    • 使用一個長度爲8的二進制數字
    • 每個像素佔用1個字節
  • 24位位圖:
    • 每個像素佔用24位,也就是3個字節,所在叫24位位圖
    • R:0-255,需要一個長度爲8的二進制數字,佔用1個字節
    • G:0-255,需要一個長度爲8的二進制數字,佔用1個字節
    • B:0-255,需要一個長度爲8的二進制數字,佔用1個字節

加載大圖片

  • 計算機把圖片所有像素信息 (圖片的總像素 * 每個像素佔用的大小) 全部解析出來,保存至內存
  • Android保存圖片像素信息,是用ARGB保存
  • 手機屏幕320*480,總像素:153600
  • 圖片寬高2400*3200,總像素7680000
  • 2400(圖片寬) / 320(手機屏幕寬) = 7
  • 3200(圖片高) / 480(手機屏幕高) = 6
  • 使用最大的比例 也就是要使用7 即可。
------ 

對圖片進行縮放

  • 獲取屏幕寬高

    Display dp = getWindowManager().getDefaultDisplay();
    int screenWidth = dp.getWidth();
    int screenHeight = dp.getHeight();
    
  • 獲取圖片寬高

    Options opts = new Options();
    //請求圖片屬性但不申請內存
    opts.inJustDecodeBounds = true;
    BitmapFactory.decodeFile("sdcard/dog.jpg", opts);
    int imageWidth = opts.outWidth;
    int imageHeight = opts.outHeight;
    
  • 圖片的寬高除以屏幕寬高,算出寬和高的縮放比例,取較大值作爲圖片的縮放比例

    int scale = 1;
    int scaleX = imageWidth / screenWidth;
    int scaleY = imageHeight / screenHeight;
    if(scaleX >= scaleY && scaleX > 1){
        scale = scaleX;
    }
    else if(scaleY > scaleX && scaleY > 1){
        scale = scaleY;
    }
    
  • 按縮放比例加載圖片

    //設置縮放比例
    opts.inSampleSize = scale;
    //爲圖片申請內存
    opts.inJustDecodeBounds = false;
    Bitmap bm = BitmapFactory.decodeFile("sdcard/dog.jpg", opts);
    iv.setImageBitmap(bm);

--------------

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){
scale = scaleWidth;
}
else if(scaleWidth < scaleHeight && scaleHeight >= 1){
scale = scaleHeight;
}
//設置縮放比例
opt.inSampleSize = scale;
opt.inJustDecodeBounds = false;
Bitmap bm = BitmapFactory.decodeFile("sdcard/dog.jpg", opt);
ImageView iv = (ImageView) findViewById(R.id.iv);
iv.setImageBitmap(bm);
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章