【问题标题】:How to load local image in Android WebView如何在 Android WebView 中加载本地图像
【发布时间】:2017-07-05 02:39:14
【问题描述】:

我正在尝试将存储在数据库中的包含图像的 html 字符串加载到WebView 中。图像存储在内部存储器中。我给出了对 html 字符串的引用。但它不起作用。有什么帮助吗?

String content="<p>Can we have a rotational" +
    " symmetry of order more than 1 whose angle of rotation is&nbsp;</p>\n" +
    "\n <p>(i)&nbsp;<img alt=\"45\\degree\" src=\"file:///storage/emulated/01484890695248.jpg\" /></p>\n" +
    "\n<p>(ii)&nbsp;<img alt=\"35\\degree\" src=\"file:///storage/emulated/01484890697301.jpg\" /></p>";

WebView00.loadDataWithBaseURL("", content, "text/html","UTF-8", "");
WebView00.getSettings();

【问题讨论】:

标签: android image webview


【解决方案1】:

这样试试

String base = Environment.getExternalStorageDirectory().getAbsolutePath().toString();
String imagePath = "file://"+ base + "/image_name.jpg";
String html = "<html><head></head><body> <img src=\""+ imagePath + "\"> </body></html>";
webView.loadDataWithBaseURL("", html, "text/html","utf-8", "");

【讨论】:

  • 非常感谢。在网上搜索了 3 个小时。
  • 对不起。不知道这个功能.. :(
  • 你是如何定义webView的?
  • 这不再适用于 Android 11 存储策略。
【解决方案2】:

将图像放在您的assets 文件夹中。然后使用对应的前缀

file:///android_asset/

【讨论】:

    【解决方案3】:

    问题出在文件路径上

    file:///storage/emulated/01484890695248.jpg
    

    应该是

    file:///storage/emulated/0/01484890695248.jpg
    

    感谢@Charuක 的帮助..

    【讨论】:

      【解决方案4】:

      在最新的 android 版本中,我们无法访问诸如 assets 、存储中的文件等资源。 https://developer.android.com/reference/androidx/webkit/WebViewAssetLoader 是继续进行的最佳指南。 WebViewAssetLoader 及其内部类有助于访问它们。

      您可以查看以下示例代码。

          final WebViewAssetLoader assetLoader = new WebViewAssetLoader.Builder()
                  .addPathHandler("/assets/", new WebViewAssetLoader.AssetsPathHandler(this)) //****for assets****
                  .addPathHandler("/images/", new WebViewAssetLoader.InternalStoragePathHandler(context, getFilesDir()))//****for files****
                  .build();
      
          webView.setWebViewClient(new WebViewClient() {
              @Override
              public WebResourceResponse shouldInterceptRequest(WebView view,
                                                                WebResourceRequest request) {
                  return assetLoader.shouldInterceptRequest(request.getUrl());
              }
          });
      
          String assetsPic = "<img width='42px' height='58px' src='https://appassets.androidplatform.net/assets/pic.png'/>";
          String storagePic = "<img width='42px' height='58px' src='https://appassets.androidplatform.net/images/pic.jpg'/>";
          webView.loadData(assetsPic+"<br>"+storagePic, "text/html", "UTF-8");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-07-23
        • 2014-06-21
        • 1970-01-01
        • 1970-01-01
        • 2017-04-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多