Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 讀取 Assets 圖片資源並儲存至 SD 卡的實作範例

編輯:Android 開發實例

本文分享一個實用小範例:如何從 Assets 目錄讀取圖片資源,轉換成 Bitmap 後再儲存到 SD 卡中。核心流程可分為三個步驟——讀取位元組資料、將位元組轉為 Bitmap、以及把 Bitmap 壓縮寫入檔案。

以下程式碼展示了完整的實作。類別 ReadBitmap 先透過 AssetManager 開啟指定的資源檔,依陣列中定義的長度分段讀取資料,再逐段轉成圖片並存檔:

public class ReadBitmap {
public void readByte(Context c, String name, int indexInt) {
byte[] b = null;
int[] intArrat = c.getResources().getIntArray(indexInt);
try {
AssetManager am = null;
am = c.getAssets();
InputStream is = am.open(name);
for (int i = 0; i < intArrat.length; i++) {
b = new byte[intArrat[i]];
// 讀取數據
is.read(b);
saveMyBitmap(Bytes2Bimap(b), MainActivity.DIR+name+i+".jpg");
}
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}

接著是將位元組陣列轉換為 Bitmap 的輔助方法 Bytes2Bimap(),以及把 Bitmap 以 JPEG 格式壓縮寫入檔案的 saveMyBitmap():

public static Bitmap Bytes2Bimap(byte[] b) {
if (b.length != 0) {
return BitmapFactory.decodeByteArray(b, 0, b.length);
} else {
return null;
}
}

public static boolean saveMyBitmap(Bitmap bmp, String path) {
File f = new File(path);
try {
f.createNewFile();
FileOutputStream fOut = new FileOutputStream(f);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.flush();
fOut.close();
return true;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return false;
}
}

整體而言,這個範例示範了如何從 Assets 讀取資源、分段處理位元組資料,最後透過 Bitmap.compress() 將圖片以指定品質寫入 SD 卡。實作時別忘了在清單檔中加上讀寫外部儲存空間的權限。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved