我有一个macOS应用程序,允许用户通过NSOpenPanel选择降价文件。
let mdUrl = openPanel.urls.first!
let baseUrl = mdUrl.deletingLastPathComponent()
let md = try! String(contentsOf: mdUrl)
let html = try! Down(markdownString: md).toHTML()
webView.loadHTMLString(html, baseURL: baseUrl)
问题在于与选定md文件位于同一级别的图像文件夹中的图像没有被加载。这是由webView加载的html-beeing的示例:
<!DOCTYPE html>
<html>
<body>
<p><img src="Images/Exampleimage.png" alt="" /></p>
</body>
</html>
baseUrl包含具有指定图像的Images目录。我该怎么做才能使图像正确加载和显示?
答案 0 :(得分:0)
在这种情况下,您必须将图像表示为Base64 String,请尝试以下代码
func getImageString(imageLocalPath: String) -> String? {
//get UIImage from localPath
let image:UIImage = // some method
if let _image = image {
// assume image is png, if not use relevant constrauction
var data = UIImagePNGRepresentation(_image)!
if let _data = data {
let data64 = _data.base64EncodedString(options:
Data.Base64EncodingOptions.endLineWithCarriageReturn)
return "<img src='data:image/\(format);base64," + data64 + "' height=200 width=400>"
}
}
return nil
}
按如下所示添加图像的条纹,然后应出现
var data64 = getImageString(//image_local path)
"<img src='data:image/\(format);base64," + data64 + "' height=200 width=400>"