Android Bitmap 相關

http://yelinsen.iteye.com/blog/844711

android 中的 Bitmap 相關 收藏 

一、Bitmap轉Drawable 
        Bitmap bm=xxx; //xxx根據你的情況獲取 
        BitmapDrawable bd=BitmapDrawable(bm); 
        Android開發網提示因爲BtimapDrawable是Drawable的子類,最終直接使用bd對象即可。 
二、 Drawable轉Bitmap 
        轉成Bitmap對象後,可以將Drawable對象通過Android的SK庫存成一個字節輸 出流,最終還可以保存成爲jpg和png的文件。 
        Drawable d=xxx; //xxx根據自己的情況獲取drawable 
        BitmapDrawable bd = (BitmapDrawable) d; 
        Bitmap bm = bd.getBitmap(); 
        最終bm就是我們需要的Bitmap對象了。 

Bitmap 相關 

1. Bitmap比較特別 因爲其不可創建 而只能藉助於BitmapFactory 而根據圖像來源又可分以下幾種情況: 

* png圖片 如:R.drawable.ic_call_log_list_incoming_call 

Java代碼  收藏代碼
  1. Bitmap bmp = BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_call_log_list_incoming_call);    
  2.   
  3. Bitmap bmp = BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_call_log_list_incoming_call);   

* 圖像文件 如: /sdcard/dcim/ic_call_log_list_incoming_call.jpeg 

Java代碼  收藏代碼
  1. Bitmap bmp = BitmapFactory.decodeFile("/sdcard/dcoim/ic_call_log_list_incoming_call.jpeg")    
  2. Bitmap bmp = BitmapFactory.decodeFile("/sdcard/dcoim/ic_call_log_list_incoming_call.jpeg")   


2. Bitmap 相關應用 

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

* 創建目標文件的File 

Java代碼  收藏代碼
  1. File fImage = new File("/sdcard/dcim","ic_call_log_list_incoming_call.jpeg");     
  2.     
  3. FileOutputStream iStream = new FileOutputStream(fImage);    
  4.   
  5. File fImage = new File("/sdcard/dcim","ic_call_log_list_incoming_call.jpeg");  
  6.   
  7. FileOutputStream iStream = new FileOutputStream(fImage);   


* 取出Bitmap oriBmp 

Java代碼  收藏代碼
  1. oriBmp.compress(CompressFormat.JPEG, 100, iStream);    
  2.   
  3. 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等貌似都可以,自己寫的: 
Java代碼  收藏代碼
  1. public void saveMyBitmap(String bitName) throws IOException {  
  2.                         File f = new File("/sdcard/Note/" + bitName + ".png");  
  3.                         f.createNewFile();  
  4.                         FileOutputStream fOut = null;  
  5.                         try {  
  6.                                 fOut = new FileOutputStream(f);  
  7.                         } catch (FileNotFoundException e) {  
  8.                                 e.printStackTrace();  
  9.                         }  
  10.                         mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);  
  11.                         try {  
  12.                                 fOut.flush();  
  13.                         } catch (IOException e) {  
  14.                                 e.printStackTrace();  
  15.                         }  
  16.                         try {  
  17.                                 fOut.close();  
  18.                         } catch (IOException e) {  
  19.                                 e.printStackTrace();  
  20.                         }  
  21.                 }  


- 得到網路圖片 

定義網絡圖片對應的BufferedInputStream 
Java代碼  收藏代碼
  1. //圖片的鏈接地址     
  2. String icoURI = "http://202.140.96.134:8080/FS-RSS/img/ic_call_log_list_incoming_call.png";     
  3.     
  4. URL imgURL = new URL(iu);     
  5. URLConnection conn = imgURL.openConnection();     
  6.                  
  7. conn.connect();     
  8. InputStream is = conn.getInputStream();     
  9.                  
  10. BufferedInputStream bis = new BufferedInputStream(is);   
  11.   
  12. //圖片的鏈接地址  
  13. String icoURI = "http://202.140.96.134:8080/FS-RSS/img/RN.png";  
  14.   
  15. URL imgURL = new URL(iu);  
  16. URLConnection conn = imgURL.openConnection();  
  17.      
  18. conn.connect();  
  19. InputStream is = conn.getInputStream();  
  20.      
  21. BufferedInputStream bis = new BufferedInputStream(is);   
  22.   
  23. //下載之  
  24. Bitmap bmp = BitmapFactory.decodeStream(bis);    
  25.   
  26. Bitmap bmp = BitmapFactory.decodeStream(bis);   
  27.   
  28. //關閉Stream  
  29. bis.close();     
  30.     
  31. is.close();    
  32.    


位圖是我們開發中最常用的資源,畢竟一個漂亮的界面對用戶是最有吸引力的。 
1. 從資源中獲取位圖 

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

當然,首先需要獲取資源: 

        Resources res=getResources(); 

使用BitmapDrawable獲取位圖 

   1.使用BitmapDrawable (InputStream is)構造一個BitmapDrawable; 
   2.使用BitmapDrawable類的getBitmap()獲取得到位圖; 

Java代碼  收藏代碼
  1. // 讀取InputStream並得到位圖  
  2. InputStream is=res.openRawResource(R.drawable.pic180);  
  3. BitmapDrawable bmpDraw=new BitmapDrawable(is);  
  4. Bitmap bmp=bmpDraw.getBitmap();  


或者採用下面的方式: 
Java代碼  收藏代碼
  1. BitmapDrawable bmpDraw=(BitmapDrawable)res.getDrawable(R.drawable.pic180);  
  2. Bitmap bmp=bmpDraw.getBitmap();  


使用BitmapFactory獲取位圖 

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

使用BitmapFactory類decodeStream(InputStream is)解碼位圖資源,獲取位圖。 

     Bitmap bmp=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對象顯示位圖 

       
Java代碼  收藏代碼
  1. // 獲取位圖  
  2.         Bitmap bmp=BitmapFactory.decodeResource(res, R.drawable.pic180);  
  3.         // 轉換爲BitmapDrawable對象  
  4.         BitmapDrawable bmpDraw=new BitmapDrawable(bmp);  
  5.         // 顯示位圖  
  6.         ImageView iv2 = (ImageView)findViewById(R.id.ImageView02);  
  7.        iv2.setImageDrawable(bmpDraw);  


使用Canvas類顯示位圖 

這兒採用一個繼承自View的子類Panel,在子類的OnDraw中顯示 
Java代碼  收藏代碼
  1. public class MainActivity extends Activity {  
  2.     /** Called when the activity is first created. */  
  3.     @Override  
  4.     public void onCreate(Bundle savedInstanceState) {  
  5.         super.onCreate(savedInstanceState);  
  6.         setContentView(new Panel(this));  
  7.     }  
  8.       
  9.     class Panel extends View{            
  10.         public Panel(Context context) {   
  11.             super(context);  
  12.         }       
  13.         public void onDraw(Canvas canvas){   
  14.             Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.pic180);   
  15.             canvas.drawColor(Color.BLACK);   
  16.             canvas.drawBitmap(bmp, 1010null);   
  17.         }   
  18.     }  
  19. }  

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(float sx, float sy) (Preconcat the current matrix with the specified scale.),不過要注意此時整個畫布都縮放了。 

(4)藉助Matrix: 

          
Java代碼  收藏代碼
  1. Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.pic180);   
  2.            Matrix matrix=new Matrix();  
  3.            matrix.postScale(0.2f, 0.2f);  
  4.            Bitmap dstbmp=Bitmap.createBitmap(bmp,0,0,bmp.getWidth(),  
  5.            bmp.getHeight(),matrix,true);  
  6.            canvas.drawColor(Color.BLACK);   
  7.            canvas.drawBitmap(dstbmp, 1010null);   


5. 位圖旋轉 

同樣,位圖的旋轉也可以藉助Matrix或者Canvas來實現。 
Java代碼  收藏代碼
  1. Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.pic180);   
  2. Matrix matrix=new Matrix();  
  3. matrix.postScale(0.8f, 0.8f);  
  4. matrix.postRotate(45);  
  5. Bitmap dstbmp=Bitmap.createBitmap(bmp,0,0,bmp.getWidth(),  
  6. bmp.getHeight(),matrix,true);  
  7. canvas.drawColor(Color.BLACK);  
  8. canvas.drawBitmap(dstbmp, 1010null);  


旋轉效果: 

image 

image 


6.圖片水印的生成方法 

生成水印的過程。其實分爲三個環節:第一,載入原始圖片;第二,載入水印圖片;第三,保存新的圖片。 
Java代碼  收藏代碼
  1. /** 
  2. *     * create the bitmap from a byte array 
  3. *     * 
  4. *     * @param src the bitmap object you want proecss 
  5. *     * @param watermark the water mark above the src 
  6. *     * @return return a bitmap object ,if paramter's length is 0,return null 
  7. *     */  
  8. *    private Bitmap createBitmap( Bitmap src, Bitmap watermark )   
  9. *    {   
  10. *        String tag = "createBitmap";   
  11. *        Log.d( tag, "create a new bitmap" );   
  12. *        if( src == null )   
  13. *        {   
  14. *            return null;   
  15. *        }   
  16. *   
  17. *        int w = src.getWidth();   
  18. *        int h = src.getHeight();   
  19. *        int ww = watermark.getWidth();   
  20. *        int wh = watermark.getHeight();   
  21. *        //create the new blank bitmap   
  22. *        Bitmap newb = Bitmap.createBitmap( w, h, Config.ARGB_8888 );//創建一個新的和SRC長度寬度一樣的位圖   
  23. *        Canvas cv = new Canvas( newb );   
  24. *        //draw src into   
  25. *        cv.drawBitmap( src, 00null );//在 0,0座標開始畫入src   
  26. *        //draw watermark into   
  27. *        cv.drawBitmap( watermark, w - ww + 5, h - wh + 5null );//在src的右下角畫入水印   
  28. *        //save all clip   
  29. *        cv.save( Canvas.ALL_SAVE_FLAG );//保存   
  30. *        //store   
  31. *        cv.restore();//存儲   
  32. *        return newb;   
  33. *    }   


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中的核心代碼是: 
Java代碼  收藏代碼
  1. int px = getMeasuredWidth();  
  2.   
  3. int py = getMeasuredWidth();  
  4.   
  5. // Draw background  
  6.   
  7. canvas.drawRect(00, px, py, backgroundPaint);  
  8.   
  9. canvas.save();  
  10.   
  11. canvas.rotate(90, px/2, py/2);                 
  12.   
  13. // Draw up arrow  
  14.   
  15. canvas.drawLine(px / 200, py / 2, linePaint);                 
  16.   
  17. canvas.drawLine(px / 20, px, py / 2, linePaint);  
  18.   
  19. canvas.drawLine(px / 20, px / 2, py, linePaint);  
  20.   
  21. canvas.restore();  
  22.   
  23. // Draw circle  
  24.   
  25. canvas.drawCircle(px - 10, py - 1010, linePaint);  


效果如圖1所示: 

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

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章