H5中不能直接使用本地路径显示图片,可以将图片转为base64显示,示例参考如下:import { webview } from '@kit.ArkWeb'; import common from '@ohos.app.ability.common'; import fs from '@ohos.file.fs'; import { util } from '@kit.ArkTS'; // 获取应用文件路径 let context = getContext(this) as common.UIAbilityContext; let pathDir = context.filesDir; // 应用通用文件路径 let filePath = pathDir + '/picture.png' let arrayBuff = context.resourceManager.getMediaContentSync($r('app.media.startIcon')).buffer let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); fs.writeSync(file.fd, arrayBuff) fs.closeSync(file); @Entry @Component struct shaxiangtupian { private webviewController: webview.WebviewController = new webview.WebviewController(); build() { Column() { Web({ src: $rawfile('资源引用'), controller: this.webviewController }) .width('100%') .height('50%') Button("转base64显示图片") .onClick(() => { let filePath = pathDir + "/picture.png"; let file1 = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); let array: ArrayBuffer = new ArrayBuffer(fs.statSync(file1.fd).size) fs.readSync(file1.fd, array) let unit = new Uint8Array(array) let base64 = new util.Base64Helper(); let mystr = "data:image/png;base64," + base64.encodeToStringSync(unit); let base64Str = "myFunction(\"" + mystr + "\")" this.webviewController.runJavaScript(base64Str) console.log(`wsf: resultBase64Str = ${mystr}`) }) } } }<!DOCTYPE html> <html> <head> </head> <body> </div> <script> function myFunction(base64str) { var img = new Image(); img.width = 200; img.height = 200; img.src = base64str; document.body.appendChild(img); } </script> </body> </html>
H5中不能直接使用本地路径显示图片,可以将图片转为base64显示,示例参考如下: