Android學習之位圖BitMap
BitMap代表一張位圖,擴充名可以是.bmp或者.dib。位圖是Windows标準格式圖形檔案,它将圖像定義為由點(像素)組成,每個點可以由多種色彩表示,包括2、4、8、16、24和32位色彩。例如,一幅1024×768分辨率的32位真彩圖檔,其所占存儲位元組數為:1024×768×32/8=3072KB
位圖檔案圖像效果好,但是非壓縮格式的,需要占用較大存儲空間,不利于在網絡上傳送。jpg格式則恰好彌補了位圖檔案這個缺點。
在android系統當中,bitmap是圖像處理最重要的類之一。用它可以擷取圖像檔案資訊,進行圖像剪切、旋轉、縮放等操作,并可以指定格式儲存圖像檔案。
下面主要介紹BitMap的用法:
1.從資源檔案中擷取
1 Bitmap rawBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.img1);
2.從SD卡中得到圖檔

1 (方法1)
2 String SDCarePath=Environment.getExternalStorageDirectory().toString();
3 String filePath=SDCarePath+"/"+"haha.jpg";
4 Bitmap rawBitmap1 = BitmapFactory.decodeFile(filePath, null);
5 (方法2)
6 InputStream inputStream=getBitmapInputStreamFromSDCard("haha.jpg");
7 Bitmap rawBitmap2 = BitmapFactory.decodeStream(inputStream);

3.設定圖檔的圓角,傳回設定後的BitMap

1 public Bitmap toRoundCorner(Bitmap bitmap, int pixels) {
2 Bitmap roundCornerBitmap = Bitmap.createBitmap(bitmap.getWidth(),
3 bitmap.getHeight(), Config.ARGB_8888);
4 Canvas canvas = new Canvas(roundCornerBitmap);
5 int color = 0xff424242;// int color = 0xff424242;
6 Paint paint = new Paint();
7 paint.setColor(color);
8 // 防止鋸齒
9 paint.setAntiAlias(true);
10 Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
11 RectF rectF = new RectF(rect);
12 float roundPx = pixels;
13 // 相當于清屏
14 canvas.drawARGB(0, 0, 0, 0);
15 // 先畫了一個帶圓角的矩形
16 canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
17 paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
18 // 再把原來的bitmap畫到現在的bitmap!!!注意這個了解
19 canvas.drawBitmap(bitmap, rect, rect, paint);
20 return roundCornerBitmap;
21 }

4.将圖檔高寬和的大小kB壓縮

1 //得到圖檔原始的高寬
2 int rawHeight = rawBitmap.getHeight();
3 int rawWidth = rawBitmap.getWidth();
4 // 設定圖檔新的高寬
5 int newHeight = 500;
6 int newWidth = 500;
7 // 計算縮放因子
8 float heightScale = ((float) newHeight) / rawHeight;
9 float widthScale = ((float) newWidth) / rawWidth;
10 // 建立立矩陣
11 Matrix matrix = new Matrix();
12 matrix.postScale(heightScale, widthScale);
13 // 設定圖檔的旋轉角度
14 // matrix.postRotate(-30);
15 // 設定圖檔的傾斜
16 // matrix.postSkew(0.1f, 0.1f);
17 // 将圖檔大小壓縮
18 // 壓縮後圖檔的寬和高以及kB大小均會變化
19 Bitmap newBitmap = Bitmap.createBitmap(rawBitmap, 0, 0, rawWidth,
20 rawWidth, matrix, true);

5.将Bitmap轉換為Drawable Drawable轉Bitmap
1 Drawable newBitmapDrawable = new BitmapDrawable(Bitmap);
2 //如果要擷取BitMapDrawable中所包裝的BitMap對象,可以用getBitMap()方法;
3 Bitmap bitmap = newBitmapDrawable.getBitmap();
6.由于前面建立的Bitmap所占用的記憶體還沒有回收,而導緻引發OutOfMemory錯誤,是以用下面方法判斷是否回收。
1 if(!bitmap.isRecycled())
2 {
3 bitmap.recycle()
4 }