天天看點

Android Bitmap 位圖相關

Bitmap相關

1. Bitmap比較特别因為其不可建立而隻能借助于BitmapFactory 而根據圖像來源又可分以下幾種情況:      

*png圖檔 如:R.drawable.tianjin

Bitmap bmp = BitmapFactory.decodeResource(this.getResources(), R.drawable.tianjin); 
Bitmap bmp = BitmapFactory.decodeResource(this.getResources(), R.drawable.tianjin);           

* 圖像檔案 如: /sdcard/dcim/tianjin.jpeg

Bitmap bmp = BitmapFactory.decodeFile("/sdcard/dcoim/tianjin.jpeg") 
Bitmap bmp = BitmapFactory.decodeFile("/sdcard/dcoim/tianjin.jpeg")           

2.Bitmap 相關應用

- 本地儲存 即 把 Bitmap 儲存在sdcard中

* 建立目标檔案的File

File fImage = new File("/sdcard/dcim","beijing.jpeg");  
FileOutputStream iStream = new FileOutputStream(fImage); 
File fImage = new File("/sdcard/dcim","beijing.jpeg");
FileOutputStream iStream = new FileOutputStream(fImage);           

* 取出Bitmap oriBmp

oriBmp.compress(CompressFormat.JPEG, 100, iStream); 
oriBmp.compress(CompressFormat.JPEG, 100, iStream);           

上次一位仁兄告訴我的方法:

參照Bitmap 的API方法compress(Bitmap.CompressFormat format, int quality, OutputStream stream)

Write a compressed version of the bitmap to the specified outputstream.

寫到輸出流裡,就儲存到檔案了。

可以儲存為幾種格式:png,gif等貌似都可以,自己寫的:

public void saveMyBitmap(String bitName) throws IOException {
	File f = new File("/sdcard/Note/" + bitName + ".png");
	f.createNewFile();
	FileOutputStream fOut = null;
	try {
		fOut = new FileOutputStream(f);
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	}
	mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
	try {
		fOut.flush();
	} catch (IOException e) {
		e.printStackTrace();
	}
	try {
		fOut.close();
	} catch (IOException e) {
		e.printStackTrace();
	}
}           

- 得到網路圖檔

* 定義網絡圖檔對應的BufferedInputStream

//圖檔的連結位址  
String icoURI = "http://202.140.96.134:8080/FS-RSS/img/RN.png";  
 
URL imgURL = new URL(iu);  
URLConnection conn = imgURL.openConnection();  
              
conn.connect();  
InputStream is = conn.getInputStream();  
              
BufferedInputStream bis = new BufferedInputStream(is); 
//圖檔的連結位址
String icoURI = "http://202.140.96.134:8080/FS-RSS/img/RN.png";
URL imgURL = new URL(iu);
URLConnection conn = imgURL.openConnection();
  
conn.connect();
InputStream is = conn.getInputStream();
  
BufferedInputStream bis = new BufferedInputStream(is);           

* 下載下傳之

Bitmap bmp = BitmapFactory.decodeStream(bis); 
Bitmap bmp = BitmapFactory.decodeStream(bis);
           

* 關閉Stream

bis.close();  
is.close();            

位圖相關

1. 從資源中擷取位圖

可以使用BitmapDrawable或者BitmapFactory來擷取資源中的位圖。

當然,首先需要擷取資源:Resources res=getResources();

使用BitmapDrawable擷取位圖

a. 使用BitmapDrawable (InputStream is)構造一個BitmapDrawable;

b. 使用BitmapDrawable類的getBitmap()擷取得到位圖;

// 讀取InputStream并得到位圖
InputStream is=res.openRawResource(R.drawable.pic180);
BitmapDrawable bmpDraw=new BitmapDrawable(is);
Bitmap bmp=bmpDraw.getBitmap();
//或者采用下面的方式:
BitmapDrawable bmpDraw=(BitmapDrawable)res.getDrawable(R.drawable.pic180);
Bitmap bmp=bmpDraw.getBitmap();           

使用BitmapFactory擷取位圖

(Creates Bitmap objects from varioussources, including files, streams, and byte-arrays.)

使用BitmapFactory類decodeStream(InputStreamis)解碼位圖資源,擷取位圖。

Bitmapbmp=BitmapFactory.decodeResource(res, R.drawable.pic180);

BitmapFactory的所有函數都是static,這個輔助類可以通過資源ID、路徑、檔案、資料流等方式來擷取位圖。

以上方法在程式設計的時候可以自由選擇,在Android SDK中說明可以支援的圖檔格式如下:png (preferred), jpg(acceptable), gif (discouraged),和bmp(Android SDK Support Media Format)。

2. 擷取位圖的資訊

要擷取位圖資訊,比如位圖大小、像素、density、透明度、顔色格式等,擷取得到Bitmap就迎刃而解了,這些資訊在Bitmap的手冊中,這裡隻是輔助說明以下2點:

*   在 Bitmap 中對 RGB 顔色格式使用 Bitmap.Config 定義,僅包括ALPHA_8、ARGB_4444、ARGB_8888、RGB_565,缺少了一些其他的,比如說RGB_555,在開發中可能要注意這個小問題;

*  Bitmap 還提供了 compress() 接口來壓縮圖檔,不過 AndroidSAK 隻支援 PNG 、 JPG 格式的壓縮;其他格式的需要Android開發人員自己補充了。

3. 顯示位圖

顯示位圖可以使用核心類Canvas,通過Canvas類的drawBirmap()顯示位圖,或者借助于BitmapDrawable來将Bitmap繪制到Canvas。當然,也可以通過BitmapDrawable将位圖顯示到View中。

轉換為BitmapDrawable對象顯示位圖

// 擷取位圖
Bitmap bmp=BitmapFactory.decodeResource(res, R.drawable.pic180);
// 轉換為BitmapDrawable對象
BitmapDrawable bmpDraw=new BitmapDrawable(bmp);
// 顯示位圖
ImageView iv2 = (ImageView)findViewById(R.id.ImageView02);
iv2.setImageDrawable(bmpDraw);           

使用Canvas類顯示位圖

這兒采用一個繼承自View的子類Panel,在子類的OnDraw中顯示

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new Panel(this));
    }
   
    class Panel extends View{         
        public Panel(Context context) {
            super(context);
        }    
        public void onDraw(Canvas canvas){
            Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.pic180);
            canvas.drawColor(Color.BLACK);
            canvas.drawBitmap(bmp, 10, 10, null);
        }
    }
}
           

4. 位圖縮放

(1)将一個位圖按照需求重畫一遍,畫後的位圖就是我們需要的了,與位圖的顯示幾乎一樣:drawBitmap(Bitmap bitmap, Rect src, Rect dst, Paint paint)。

(2)在原有位圖的基礎上,縮放原位圖,建立一個新的位圖:CreateBitmap(Bitmap source, int x, int y, int width, int height,Matrix m, boolean filter)

(3)借助Canvas的scale(floatsx, float sy) (Preconcat thecurrent matrix with the specified scale.),不過要注意此時整個畫布都縮放了。

(4)借助Matrix:

Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.pic180);
Matrix matrix=new Matrix();
matrix.postScale(0.2f, 0.2f);
Bitmap dstbmp=Bitmap.createBitmap(bmp,0,0,bmp.getWidth(),
bmp.getHeight(),matrix,true);
canvas.drawColor(Color.BLACK);
canvas.drawBitmap(dstbmp, 10, 10, null);           

5. 位圖旋轉

同樣,位圖的旋轉也可以借助Matrix或者Canvas來實作。

Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.pic180);
Matrix matrix=new Matrix();
matrix.postScale(0.8f, 0.8f);
matrix.postRotate(45);
Bitmap dstbmp=Bitmap.createBitmap(bmp,0,0,bmp.getWidth(),
bmp.getHeight(),matrix,true);
canvas.drawColor(Color.BLACK);
canvas.drawBitmap(dstbmp, 10, 10, null);           

旋轉效果:

Android Bitmap 位圖相關
Android Bitmap 位圖相關

6.圖檔水印的生成方法

生成水印的過程。其實分為三個環節:第一,載入原始圖檔;第二,載入水印圖檔;第三,儲存新的圖檔。

/**
 * create the bitmap from a byte array * * @param src the bitmap object
 * you want proecss * @param watermark the water mark above the src * @return
 * return a bitmap object ,if paramter's length is 0,return null
 */
private Bitmap createBitmap(Bitmap src, Bitmap watermark) {
	String tag = "createBitmap";
	Log.d(tag, "create a new bitmap");
	if (src == null) {
		return null;
	}

	int w = src.getWidth();
	int h = src.getHeight();
	int ww = watermark.getWidth();
	int wh = watermark.getHeight();
	// create the new blank bitmap
	Bitmap newb = Bitmap.createBitmap(w, h, Config.ARGB_8888);// 建立一個新的和SRC長度寬度一樣的位圖
	Canvas cv = new Canvas(newb);
	// draw src into
	cv.drawBitmap(src, 0, 0, null);// 在 0,0坐标開始畫入src
	// draw watermark into
	cv.drawBitmap(watermark, w - ww + 5, h - wh + 5, null);// 在src的右下角畫入水印
	// save all clip
	cv.save(Canvas.ALL_SAVE_FLAG);// 儲存
	// store
	cv.restore();// 存儲
	return newb;
}           

7.Canvas的save和restore

onDraw方法會傳入一個Canvas對象,它是你用來繪制控件視覺界面的畫布。

在onDraw方法裡,我們經常會看到調用save和restore方法,它們到底是幹什麼用的呢?

❑ save:用來儲存Canvas的狀态。save之後,可以調用Canvas的平移、放縮、旋轉、錯切、裁剪等操作。

❑ restore:用來恢複Canvas之前儲存的狀态。防止save後對Canvas執行的操作對後續的繪制有影響。

save和restore要配對使用(restore可以比save少,但不能多),如果restore調用次數比save多,會引發Error。save和restore之間,往往夾雜的是對Canvas的特殊操作。

例如:我們先想在畫布上繪制一個右向的三角箭頭,當然,我們可以直接繪制,另外,我們也可以先把畫布旋轉90°,畫一個向上的箭頭,然後再旋轉回來(這種旋轉操作對于畫圓周上的标記非常有用)。然後,我們想在右下角有個20像素的圓,那麼,onDraw中的核心代碼是:

int px = getMeasuredWidth();
int py = getMeasuredWidth();
// Draw background
canvas.drawRect(0, 0, px, py, backgroundPaint);
canvas.save();
canvas.rotate(90, px/2, py/2);              
// Draw up arrow
canvas.drawLine(px / 2, 0, 0, py / 2, linePaint);              
canvas.drawLine(px / 2, 0, px, py / 2, linePaint);
canvas.drawLine(px / 2, 0, px / 2, py, linePaint);
canvas.restore();
// Draw circle
canvas.drawCircle(px - 10, py - 10, 10, linePaint);           

效果如圖1所示:

Android Bitmap 位圖相關

                                            圖1

如果我們不調用save和restore會是什麼樣子呢?如圖2所示:

Android Bitmap 位圖相關

                                            圖2

從這兩個圖中,我們就能看到圓圈位置的明顯差異。不進行Canvas的save和restore操作的話,所有的圖像都是在畫布旋轉90°後的畫布上繪制的。當執行完onDraw方法,系統自動将畫布恢複回來。save和restore操作執行的時機不同,就能造成繪制的圖形不同。

本文參考: http://www.cnblogs.com/feisky/archive/2010/01/10/1643460.html