1. 程式人生 > >Bitmap類用法 詳細說明

Bitmap類用法 詳細說明

1.  BitMap類
public void recycle()——回收點陣圖佔用的記憶體空間,把點陣圖標記為Dead 
public final boolean isRecycled() ——判斷點陣圖記憶體是否已釋放 
public final int getWidth()——獲取點陣圖的寬度 
public final int getHeight()——獲取點陣圖的高度 
public final boolean isMutable()——圖片是否可修改 
public int getScaledWidth(Canvas canvas)——獲取指定密度轉換後的影象的寬度 
public int getScaledHeight(Canvas canvas)——獲取指定密度轉換後的影象的高度 
public boolean compress(CompressFormat format, int quality, OutputStream stream)——按指定的圖片格式以及畫質,將圖片轉換為輸出流。 
format:Bitmap.CompressFormat.PNG或Bitmap.CompressFormat.JPEG 
quality:畫質,0-100.0表示最低畫質壓縮,100以最高畫質壓縮。對於PNG等無損格式的圖片,會忽略此項設定。 

常用的靜態方法: 
public static Bitmap createBitmap(Bitmap src) ——以src為原圖生成不可變得新影象 
public static Bitmap createScaledBitmap(Bitmap src, int dstWidth, 
            int dstHeight, boolean filter)——以src為原圖,建立新的影象,指定新影象的高寬以及是否可變。 
public static Bitmap createBitmap(int width, int height, Config config)——建立指定格式、大小的點陣圖 
public static Bitmap createBitmap(Bitmap source, int x, int y, int width, int height)以source為原圖,建立新的圖片,指定起始座標以及新影象的高寬。 
2. BitmapFactory工廠類:
Option 引數類: 
public boolean inJustDecodeBounds——如果設定為true,不獲取圖片,不分配記憶體,但會返回圖片的高度寬度資訊。 
public int inSampleSize——圖片縮放的倍數。如果設為4,則寬和高都為原來的1/4,則圖是原來的1/16。 
public int outWidth——獲取圖片的寬度值 
public int outHeight——獲取圖片的高度值 
public int inDensity——用於點陣圖的畫素壓縮比 
public int inTargetDensity——用於目標點陣圖的畫素壓縮比(要生成的點陣圖) 
public boolean inScaled——設定為true時進行圖片壓縮,從inDensity到inTargetDensity。

使用BitmapFactory  可從資源files, streams, and byte-arrays中解碼生成Bitmap物件。

讀取一個檔案路徑得到一個位圖。如果指定檔案為空或者不能解碼成檔案,則返回NULL。 
public static Bitmap decodeFile(String pathName, Options opts) 
public static Bitmap decodeFile(String pathName) 
讀取一個資原始檔得到一個位圖。如果點陣圖資料不能被解碼,或者opts引數只請求大小資訊時,則返回NuLL。 
(即當Options.inJustDecodeBounds=true,只請求圖片的大小資訊。) 
public static Bitmap decodeResource(Resources res, int id) 
public static Bitmap decodeResource(Resources res, int id, Options opts) 
從輸入流中解碼點陣圖 
public static Bitmap decodeStream(InputStream is) 
從位元組陣列中解碼生成不可變的點陣圖 
public static Bitmap decodeByteArray(byte[] data, int offset, int length) 

BitmapDrawable類:繼承於Drawable,你可以從檔案路徑、輸入流、XML檔案以及Bitmap中建立。 
常用的建構函式: 
Resources res=getResources();//獲取資源 
public BitmapDrawable(Resources res)——建立一個空的drawable。(Response用來指定初始時所用的畫素密度)替代public BitmapDrawable()方法(此方法不處理畫素密度) 
public BitmapDrawable(Resources res, Bitmap bitmap)——Create drawable from a bitmap 
public BitmapDrawable(Resources res, String filepath)——Create a drawable by opening a given file path and decoding the bitmap. 
public BitmapDrawable(Resources res, java.io.InputStream is)——Create a drawable by decoding a bitmap from the given input stream. 

2).顯示Bitmap
2.1) 使用Canvas類顯示點陣圖

public class Main extends Activity {        
    @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);     
        }     
    }    
}
2.2) 通過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); 
  摘自:http://www.myexception.cn/android/1353713.html
Android中Bitmap的常見操作整理一覽,需要的朋友可以參考下 摘自:http://www.jb51.net/article/32366.htm
//方法: 
//1 生成圓角Bitmap圖片 
//2 生成Bitmap縮量圖 
//3 壓縮圖片場長寬以及kB 
//注意: 
//以上程式碼,測試其中一個方法時最好註釋掉其餘的程式碼 
public class MainActivity extends Activity { 
private ImageView imageView; 
private Bitmap copyRawBitmap1; 
private Bitmap copyRawBitmap2; 
private Bitmap copyRawBitmap3; 
@Override 
public void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.main); 
imageView = (ImageView) findViewById(R.id.imageView); 
//第一種方式:從資原始檔中得到圖片 
Bitmap rawBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.haha); 
copyRawBitmap1=rawBitmap; 
copyRawBitmap2=rawBitmap; 
copyRawBitmap3=rawBitmap; 
//第二種方式:從SD卡中得到圖片(方法1) 
String SDCarePath=Environment.getExternalStorageDirectory().toString(); 
String filePath=SDCarePath+"/"+"haha.jpg"; 
Bitmap rawBitmap1 = BitmapFactory.decodeFile(filePath, null); 
//第二種方式:從SD卡中得到圖片(方法2) 
InputStream inputStream=getBitmapInputStreamFromSDCard("haha.jpg"); 
Bitmap rawBitmap2 = BitmapFactory.decodeStream(inputStream); 

//————>以下為將設定圖片的圓角 
Bitmap roundCornerBitmap=this.toRoundCorner(rawBitmap, 40); 
imageView.setImageBitmap(roundCornerBitmap); 
//————>以上為將設定圖片的圓角 

//————>以下為將圖片高寬和的大小kB壓縮 
// 得到圖片原始的高寬 
int rawHeight = rawBitmap.getHeight(); 
int rawWidth = rawBitmap.getWidth(); 
// 設定圖片新的高寬 
int newHeight = 500; 
int newWidth = 500; 
// 計算縮放因子 
float heightScale = ((float) newHeight) / rawHeight; 
float widthScale = ((float) newWidth) / rawWidth; 
// 新建立矩陣 
Matrix matrix = new Matrix(); 
matrix.postScale(heightScale, widthScale); 
// 設定圖片的旋轉角度 
//matrix.postRotate(-30); 
// 設定圖片的傾斜 
//matrix.postSkew(0.1f, 0.1f); 
//將圖片大小壓縮 
//壓縮後圖片的寬和高以及kB大小均會變化 
Bitmap newBitmap = Bitmap.createBitmap(rawBitmap, 0, 0, rawWidth,rawWidth, matrix, true); 
// 將Bitmap轉換為Drawable 
Drawable newBitmapDrawable = new BitmapDrawable(newBitmap); 
imageView.setImageDrawable(newBitmapDrawable); 
//然後將Bitmap儲存到SDCard中,方便於原圖片的比較 
this.compressAndSaveBitmapToSDCard(newBitmap, "xx100.jpg", 80); 
//問題: 
//原圖大小為625x690 90.2kB 
//如果設定圖片500x500 壓縮後大小為171kB.即壓縮後kB反而變大了. 
//原因是將:compress(Bitmap.CompressFormat.JPEG, quality, fileOutputStream); 
//第二個引數quality設定得有些大了(比如100). 
//常用的是80,剛設100太大了造成的. 
//————>以上為將圖片高寬和的大小kB壓縮 


//————>以下為將圖片的kB壓縮,寬高不變 
this.compressAndSaveBitmapToSDCard(copyRawBitmap1,"0011fa.jpg",80); 
//————>以上為將圖片的kB壓縮,寬高不變 

//————>以下為獲取SD卡圖片的縮圖方法1 
String SDCarePath1=Environment.getExternalStorageDirectory().toString(); 
String filePath1=SDCarePath1+"/"+"haha.jpg"; 
Bitmap bitmapThumbnail1=this.getBitmapThumbnail(filePath1); 
imageView.setImageBitmap(bitmapThumbnail1); 
//————>以上為獲取SD卡圖片的縮圖方法1 

//————>以下為獲取SD卡圖片的縮圖方法2 
String SDCarePath2=Environment.getExternalStorageDirectory().toString(); 
String filePath2=SDCarePath2+"/"+"haha.jpg"; 
Bitmap tempBitmap=BitmapFactory.decodeFile(filePath2); 
Bitmap bitmapThumbnail2=ThumbnailUtils.extractThumbnail(tempBitmap, 100, 100); 
imageView.setImageBitmap(bitmapThumbnail2); 
//————>以上為獲取SD卡圖片的縮圖方法2 

} 
//讀取SD卡下的圖片 
private InputStream getBitmapInputStreamFromSDCard(String fileName){ 
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { 
String SDCarePath=Environment.getExternalStorageDirectory().toString(); 
String filePath=SDCarePath+File.separator+fileName; 
File file=new File(filePath); 
try { 
FileInputStream fileInputStream=new FileInputStream(file); 
return fileInputStream; 
} catch (Exception e) { 
e.printStackTrace(); 
} 

} 
return null; 
} 


//獲取SDCard的目錄路徑功能 
private String getSDCardPath() { 
String SDCardPath = null; 
// 判斷SDCard是否存在 
boolean IsSDcardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); 
if (IsSDcardExist) { 
SDCardPath = Environment.getExternalStorageDirectory().toString(); 
} 
return SDCardPath; 
} 
//壓縮且儲存圖片到SDCard 
private void compressAndSaveBitmapToSDCard(Bitmap rawBitmap,String fileName,int quality){ 
String saveFilePaht=this.getSDCardPath()+File.separator+fileName; 
File saveFile=new File(saveFilePaht); 
if (!saveFile.exists()) { 
try { 
saveFile.createNewFile(); 
FileOutputStream fileOutputStream=new FileOutputStream(saveFile); 
if (fileOutputStream!=null) { 
//imageBitmap.compress(format, quality, stream); 
//把點陣圖的壓縮資訊寫入到一個指定的輸出流中 
//第一個引數format為壓縮的格式 
//第二個引數quality為影象壓縮比的值,0-100.0 意味著小尺寸壓縮,100意味著高質量壓縮 
//第三個引數stream為輸出流 
rawBitmap.compress(Bitmap.CompressFormat.JPEG, quality, fileOutputStream); 
} 
fileOutputStream.flush(); 
fileOutputStream.close(); 
} catch (IOException e) { 
e.printStackTrace(); 

} 
} 
} 

//獲取圖片的縮圖 
private Bitmap getBitmapThumbnail(String filePath){ 
BitmapFactory.Options options=new BitmapFactory.Options(); 
//true那麼將不返回實際的bitmap物件,不給其分配記憶體空間但是可以得到一些解碼邊界資訊即圖片大小等資訊 
options.inJustDecodeBounds=true; 
//此時rawBitmap為null 
Bitmap rawBitmap = BitmapFactory.decodeFile(filePath, options); 
if (rawBitmap==null) { 
System.out.println("此時rawBitmap為null"); 
} 
//inSampleSize表示縮圖大小為原始圖片大小的幾分之一,若該值為3 
//則取出的縮圖的寬和高都是原始圖片的1/3,圖片大小就為原始大小的1/9 
//計算sampleSize 
int sampleSize=computeSampleSize(options, 150, 200*200); 
//為了讀到圖片,必須把options.inJustDecodeBounds設回false 
options.inJustDecodeBounds = false; 
options.inSampleSize = sampleSize; 
//原圖大小為625x690 90.2kB 
//測試呼叫computeSampleSize(options, 100, 200*100); 
//得到sampleSize=8 
//得到寬和高位79和87 
//79*8=632 87*8=696 
Bitmap thumbnailBitmap=BitmapFactory.decodeFile(filePath, options); 
//儲存到SD卡方便比較 
this.compressAndSaveBitmapToSDCard(thumbnailBitmap, "15.jpg", 80); 
return thumbnailBitmap; 
} 

//參考資料: 
//http://my.csdn.net/zljk000/code/detail/18212 
//第一個引數:原本Bitmap的options 
//第二個引數:希望生成的縮圖的寬高中的較小的值 
//第三個引數:希望生成的縮量圖的總畫素 
public static int computeSampleSize(BitmapFactory.Options options,int minSideLength, int maxNumOfPixels) { 
int initialSize = computeInitialSampleSize(options, minSideLength,maxNumOfPixels); 
int roundedSize; 
if (initialSize <= 8) { 
roundedSize = 1; 
while (roundedSize < initialSize) { 
roundedSize <<= 1; 
} 
} else { 
roundedSize = (initialSize + 7) / 8 * 8; 
} 
return roundedSize; 
} 

private static int computeInitialSampleSize(BitmapFactory.Options options,int minSideLength, int maxNumOfPixels) { 
//原始圖片的寬 
double w = options.outWidth; 
//原始圖片的高 
double h = options.outHeight; 
System.out.println("========== w="+w+",h="+h); 
int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math 
.sqrt(w * h / maxNumOfPixels)); 
int upperBound = (minSideLength == -1) ? 128 : (int) Math.min( 
Math.floor(w / minSideLength), Math.floor(h / minSideLength)); 
if (upperBound < lowerBound) { 
// return the larger one when there is no overlapping zone. 
return lowerBound; 
} 
if ((maxNumOfPixels == -1) && (minSideLength == -1)) { 
return 1; 
} else if (minSideLength == -1) { 
return lowerBound; 
} else { 
return upperBound; 
} 
} 

/** 
* @param bitmap 需要修改的圖片 
* @param pixels 圓角的弧度 
* @return 圓角圖片 
*/ 
//參考資料: 
//http://blog.csdn.net/c8822882/article/details/6906768 
public Bitmap toRoundCorner(Bitmap bitmap, int pixels) { 
Bitmap roundCornerBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888); 
Canvas canvas = new Canvas(roundCornerBitmap); 
int color = 0xff424242;//int color = 0xff424242; 
Paint paint = new Paint(); 
paint.setColor(color); 
//防止鋸齒 
paint.setAntiAlias(true); 
Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); 
RectF rectF = new RectF(rect); 
float roundPx = pixels; 
//相當於清屏 
canvas.drawARGB(0, 0, 0, 0); 
//先畫了一個帶圓角的矩形 
canvas.drawRoundRect(rectF, roundPx, roundPx, paint); 
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); 
//再把原來的bitmap畫到現在的bitmap!!!注意這個理解 
canvas.drawBitmap(bitmap, rect, rect, paint); 
return roundCornerBitmap; 
} 

}