[英]android load image from my class in webview loaddatawithbaseurl
[英]Android webview loadDataWithBaseURL how load images from assets?
在我的項目中,我有一個文件:
"MyProject/assets/folder1/image1.jpg"
"MyProject/assets/folder1/index.html".
在webView中我需要打開index.html(帶圖片)。
我嘗試這段代碼:
String baseUrl = "file:///android_asset/folder1/";
webView.loadDataWithBaseURL(baseUrl, readFileAsString("index.html") , mimeType, "UTF-8", null);
但圖像無法加載。
如果我將圖像放到“ assets ”目錄( MyProject/assets/
)並使baseUrl = "file:///android_asset"
圖像正確加載;
如何從root資產目錄加載圖像,還是從assets/folder1
加載圖像?
試試這樣
WebView webview = (WebView)this.findViewById(R.id.webview);
String html = "<html><head><title>TITLE!!!</title></head>";
html += "<body><h1>Image?</h1><img src=\"icon.png\" /></body></html>";
webview.loadDataWithBaseURL("file:///android_res/drawable/", html, "text/html", "UTF-8", null);
有關更多信息,請嘗試此鏈接
我認為您必須將基礎設置為資源並將子文件夾添加到您的圖像src中,如下所示:
webView.loadDataWithBaseURL("file:///android_asset/", readAssetFileAsString("folder1/index.html"), "text/html", "UTF-8", null);
Html: <img src="folder1/image1.jpg">
這適用於Android 5.1
private String readAssetFileAsString(String sourceHtmlLocation)
{
InputStream is;
try
{
is = getContext().getAssets().open(sourceHtmlLocation);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
return new String(buffer, "UTF-8");
}
catch(IOException e)
{
e.printStackTrace();
}
return "";
}
試着這樣
try {
String filePath = null;
filePath = "Your File path";
Bitmap bitmap = null;
bitmap = BitmapFactory.decodeFile(filePath);
Log.v("Image data-->", "" + bitmap);
imageWidth = bitmap.getWidth();
imageHeight = bitmap.getHeight();
Log.e("Width", "" + imageWidth);
filePath = "file://" + filePath;
String html = "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta http-equiv=\"Content-Type\" content=\"text/html\";charset=utf-8\"/><title></title></head><body style=\"width:"
+ imageWidth
+ "px; height:"
+ imageHeight
+ "px; background:url("
+ filePath
+ ") no-repeat; position:relative;\">"
+ getDivTag(mapList)
+ "</body></html>";
Log.v("MIS", "" + html);
webview.getSettings().setSupportZoom(true);
webview.loadDataWithBaseURL(null, html, "text/html", "utf-8", null);
System.out.println(html);
} catch (Exception e) {
e.printStackTrace();
}
你有網絡許可嗎?
<uses-permission android:name="android.permission.INTERNET" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.