【问题标题】:cordova load image file from device storage科尔多瓦从设备存储中加载图像文件
【发布时间】:2020-08-26 11:21:46
【问题描述】:

我有一个图像标签,它是对应用程序目录中图像文件的 src 引用。我使用cordova.file.applicationStorageDirectory 获取应用程序目录并将其余路径添加到它(不是:我已经使用 java android studio 在其中创建了新目录和图像)。所以我的 img src 的完整路径是 file:///data/data/com.test.Dir/myfoolder/myimg.jpg 所以为了测试我像 <img id="the_img" src="file:///data/data/com.test.Dir/myfoolder/myimg.jpg" width="100" height="150"> 一样使用它,但 img 标签是空的,所以这似乎不是一个正确的方法。如何将应用目录中的图像加载到图像标签。

【问题讨论】:

    标签: android cordova local-storage


    【解决方案1】:

    您可以使用“cdvfile://”协议直接放置图像。将其用作:

    <img src="cdvfile://localhost/persistent/img/logo.png" />
    

    更多细节在这里: https://github.com/apache/cordova-plugin-file#cdvfile-protocol

    【讨论】:

    • 所以我的路径变成了 cdvfile://localhost/persistent/myfoolder/myimg.jpg ?
    • PS...图片在您的 www 文件夹中吗?
    • 没有 www 是只读的,因为它在 android_assets 中,所以我需要将图像保存在 app 目录中,并在图像标签中动态加载它们 stackoverflow.com/questions/56525675/…
    • 在这种情况下,您的路径应该是cdvfile://localhost/applicationStorageDirectory/myfolder/myimg.jpg
    【解决方案2】:

    我知道这个问题是针对 Android 上的 Cordova,但供将来参考 - 这在 iOS 上不起作用,因为最新的 WKWebView 存在 CORS 问题。您将需要手动读取文件并注入图像。像这样的:

        function loadImageFromFile(filename, index) {
            window.resolveLocalFileSystemURL(filename, function success(fileEntry) {
                fileEntry.file(function (file) {
                    var reader = new FileReader();
                    reader.onloadend = function() {
                        if (this.result) {
                            var elem = document.getElementById("imageitem");
                            var blob = new Blob([new Uint8Array(this.result)], { type: "image/png" });
                            elem.src = window.URL.createObjectURL(blob);
                        }
                    };
                    reader.readAsArrayBuffer(file);
                });
            }, function () {
                console.log("File not found: ");
            });
        }
    

    【讨论】:

      【解决方案3】:
      <img id="the_img" src="/storage/emulated/0/Android/data/com.test.Dir/files/myimg.jpg" width="100" height="150">
      

      【讨论】:

      • 请补充说明
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 2012-09-21
      • 1970-01-01
      相关资源
      最近更新 更多