編輯: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 卡。實作時別忘了在清單檔中加上讀寫外部儲存空間的權限。
用圖靈機器人 API 做一個安卓聊天機器人
前幾天看到有人用 iOS 寫了個圖靈機器人的客戶端,順手翻了官網的接入文件(https://www.tuling123.com/openapi/),發現簡單得有點意外——
Android ListView 深入講解:三種 Adapter 與自定義渲染
ListView 是 Android 開發中最常用的元件之一,它以列表形式呈現資料,並能依資料長度自動適配顯示。以下把使用方式系統整理一遍,並附可運行的示例。 列表的三
Android 登入功能範例:帳號密碼與錯誤次數管理
登入功能看似簡單,卻需要兼顧使用者體驗與安全性。Android 登入畫面通常包含帳號、密碼、登入按鈕,以及錯誤次數提示。 輸入欄位 帳號欄使用一般文字輸入即可;密碼欄則必
Android JSON 解析器:從 JSON 結構到天氣資料讀取
JSON(JavaScript Object Notation)是一種輕量、易讀的資料交換格式。相較於 XML,它更適合行動裝置與網路 API,因為結構簡單、解析速度快,