天天看點

Bitmap與byte、file、Drawable之間的互相轉換

1、Bitmap轉換成檔案:     (1)、根據指定的檔案,擷取這個檔案的輸出流     (2)、通過使用Bitmap的compress方法,設定圖檔存儲格式,圖檔的品質,并制定圖檔的存儲的輸出流。     (3)、通過重新整理輸出流,就完成Bitmap到檔案的轉換。 代碼:

public void saveBitmap(Bitmap bm) {
    Log.e("SaveBitmap", "儲存圖檔");
File f = new File("/sdcard/namecard/", "bitmap.jpg");
    if (f.exists()) {
        f.delete();
}
try {
        FileOutputStream out = new FileOutputStream(f);
bm.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
Log.i("SaveBitmap", "已經儲存");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} 
}      

2、Bitmap轉換成byte數組         根儲存成檔案的方式類似:使用ByteArrayOutputStream 代碼:

public byte[] transformBitmapToByte(Bitmap bm){
byte[] bytes = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG,90,out);
bytes = out.toByteArray();
    if (bytes == null || bytes.length <= 0){
        Log.i("transformBitmapToByte","Fail to transform data");
}
try {
        out.close();
} catch (IOException e) {
        e.printStackTrace();
}
return bytes;
}      

3、Bitmap轉換成Drawable 代碼:

private Drawable transformBitmapToDrawable(Bitmap bitmap) {
    Drawable drawable = null;
    File tempFile = new File(Environment.
            getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).
            toString(), "temp.jpg");
    if(tempFile.exists()){
        try {

            FileOutputStream out = new FileOutputStream(tempFile);
            bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();
            drawable = BitmapDrawable.createFromPath(tempFile.getAbsolutePath());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    if (drawable == null){
        Log.i("BitmapToDrawable", "Fail to transform drawable");
    }
    return drawable;
}      

4、圖檔檔案轉換成Bitmap     通過使用BitmapFactory中的方法可以直接擷取一個Bitmap對象。