我已經把圖檔抓到Local端了,用 openFileOutput 寫入了。
方法1:
注意!!
用loadData時,要把 '#', '%', '\', '?' 分別轉換成 %23, %25, %27, %3f
且因為這個方法無法從遠端讀取資料,必須要把圖檔讀出來做過Base64 Encode
( Android 2.2 才有 Base64.java這個 Class,沒有需要自己去偷過來用!)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
方法2:
個人較推薦,較不會犯錯。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); |
沒有留言:
張貼留言