2012年3月6日 星期二

Android Load Local Image To WebView

前提:
我已經把圖檔抓到Local端了,用 openFileOutput 寫入了。

方法1:
注意!!
用loadData時,要把 '#', '%', '\', '?' 分別轉換成 %23, %25, %27, %3f
且因為這個方法無法從遠端讀取資料,必須要把圖檔讀出來做過Base64 Encode
( Android 2.2 才有 Base64.java這個 Class,沒有需要自己去偷過來用!)
InputStream is;
try {
is = openFileInput(fileName);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[10240];
int count;
while(-1 != (count = is.read(buffer, 0, buffer.length))) {
baos.write(buffer, 0, count);
}
baos.flush();
byte[] imageRaw = baos.toByteArray();
baos.close();
is.close();
//Base64 is copy from Android 2.2 source code due to the min SDK version is 2.1.
String image64 = Base64.encodeToString(imageRaw, Base64.DEFAULT);
String html = String.format("<body style=\"margin:0;padding:0;border:0;\"><img width=\"100%%25\" src=\"data:image/jpeg;base64,%s\" /></div>", image64);
getWebView().loadData(html, "text/html; charset=UTF-8", null);
} catch (Exception e) {
e.printStackTrace();
onFail(e);
}
view raw Demo.java hosted with ❤ by GitHub


方法2:
個人較推薦,較不會犯錯。
File file = getFileStreamPath(fileName);
String path = file.getAbsolutePath();
String html = "<body style=\"margin:0;padding:0;border:0;\"><img width=\"100%\" src=\"file://" + path + "\" /></body>";
getWebView().loadDataWithBaseURL("http://noneed.url", html, "text/html", "UTF-8", "about:blank");
view raw gistfile1.java hosted with ❤ by GitHub

沒有留言:

張貼留言