在我的项目中,我有一个文件:
"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);
但图片无法加载。
如果我将图片放入“资源”目录(MyProject/assets/
)并正确加载baseUrl = "file:///android_asset"
张图片;
如何从root资产目录加载图像,以及从assets/folder1
加载图像?
答案 0 :(得分:13)
试试这个
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);
有关详细信息,请尝试此link
答案 1 :(得分:5)
我认为您必须将基础设置为资源并将子文件夹添加到图像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 "";
}
答案 2 :(得分:1)
尝试喜欢这个
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();
}
答案 3 :(得分:-11)
您是否已获得互联网许可?
<uses-permission android:name="android.permission.INTERNET" />