【问题标题】:Loading an image from local android storage to WebView将图像从本地 android 存储加载到 WebView
【发布时间】:2019-10-09 18:11:03
【问题描述】:

是否可以从本地 android 手机存储中将图片加载到 WebView ?基本上我想做的是,拍照,然后在 WebView 中显示该图片(如预览图片),然后在填写更多信息后,将该图片与整个数据一起上传到数据库。一切都在 android studio Java 代码中,WebView 显然是我从 assets 文件夹中加载的 .html 文件。

我在想也许我需要创建一个<img id="image"></img> 然后以某种方式获取 ID?但是即使我设法获得了ID,我如何将图片存储在里面?

我已经完成了所有相机的工作,所以我可以打开相机(通过我的 WebView)并拍照,图片保存在我知道的路径中,并且我知道图片的名称。另外我目前可以从手机中选择图片,但问题是它只选择而不做任何事情,所以选择没有用。

如果您需要任何代码,我会编辑。

【问题讨论】:

  • 相关:How to load local image in Android WebView 但也许你今天必须做点不一样的事,另一个帖子已经有 2.5 年历史了
  • 谢谢,我已经完成了该问题中的建议,但是如果您知道我的意思,它会从字符串中打开一个新的“html”。我需要它在我当前的 html 内打开。或者我可以复制我当前的 .html,但添加存储该图像的位置,但我不知道如何将该图片准确地放入那些 <img> 标记中。您提供的链接中的方法有效,但不是我需要的...
  • 只把图片名放在src标签里,把图片放在和html文件一样的assets目录下。但是您不需要任何 html 来显示图像。您可以直接从 webview 中的资产加载图像。
  • 如果 html 来自资产并且您的图片例如在 /storage/emulated/0/DCIM/Camera 中,那么 src 标签应该看起来像 file:///storage/emulated/0/DCIM/Camera/mypicture.jpg;` 您可以通过只需使用该 url 调用 loadUrl()。

标签: android android-studio android-webview


【解决方案1】:

所以我找到了我想做的事情的解决方案,如果有一天有人想知道这篇文章并想知道解决方案,我会在这里发布答案。

基本上在拍照后我调用 javascript 函数将拍摄的图像放入我的.html 文件中<img></img> 标记之间作为源。 这是我在MainActivity.java 中的onActivityResult

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE && resultCode == Activity.RESULT_OK) {
            //Getting the full image path of the image taken
            final String imagePath = "file://"+ currentPhotoPath;
            webView.post(new Runnable() {
                @Override
                public void run() {
                    webView.evaluateJavascript("postImage('" + imagePath + "')", null);
                }
            });
            getLocation();
            if (data == null) {
                //Display an error
                Log.d("performClick", "Error: data == null");
                return;
            }
        }
    }

它的作用是调用javascript函数postImage并将imagePath作为参数传递,我的hello.js文件中的函数是:

function postImage(imagePath){
    document.body.innerHTML = "<img src=\""+ imagePath + "\">";
}

现在,一旦我拍摄了照片,它就会作为图像显示在我的 WebView 上,而无需重新加载页面或加载仅包含图像的另一个 URL。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-23
    • 1970-01-01
    • 1970-01-01
    • 2012-07-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-12
    相关资源
    最近更新 更多