[markdown] IDEA-271643 fix saving images when exporting markdown to HTML
authorElya.Mamedova <elya.mamedova@jetbrains.com>
Sat, 24 Jul 2021 18:15:20 +0000 (21:15 +0300)
committerintellij-monorepo-bot <intellij-monorepo-bot-no-reply@jetbrains.com>
Mon, 2 Aug 2021 09:22:10 +0000 (09:22 +0000)
GitOrigin-RevId: 9123beeecec2e8173f9bf25d0d99b6bc8dee18f4

plugins/markdown/src/org/intellij/plugins/markdown/ui/preview/jcef/HtmlExporter.kt

index 310b9c250da2a3e34ef8e4846b3eb1a408bcb95e..4841730d9deb521f23e768ac41c5d31c90843a31 100644 (file)
@@ -68,11 +68,11 @@ class HtmlExporter(htmlSource: String,
 
   private fun inlineImagesContent(images: Elements) {
     images.forEach {
-      val url = it.attr("src")
-      val content = getResource(url)
+      val imgSrc = getImgUriWithProtocol(it.attr("src"))
+      val content = getResource(imgSrc)
 
-      if (content != null && url.isNotEmpty()) {
-        it.attr("src", encodeImage(url, content))
+      if (content != null && imgSrc.isNotEmpty()) {
+        it.attr("src", encodeImage(imgSrc, content))
       }
     }
   }
@@ -86,20 +86,26 @@ class HtmlExporter(htmlSource: String,
 
   private fun saveImages(images: Elements) {
     images.forEach {
-      val url = it.attr("src")
-      val content = getResource(url)
+      val imgSrc = it.attr("src")
+      val imgUri = getImgUriWithProtocol(imgSrc)
+      val content = getResource(imgUri)
 
-      if (content != null && url.isNotEmpty()) {
-        val savedImgFile = getSavedImageFile(savingSettings.resourceDir, url)
+      if (content != null && imgSrc.isNotEmpty()) {
+        val savedImgFile = getSavedImageFile(savingSettings.resourceDir, imgSrc)
         FileUtil.createIfDoesntExist(savedImgFile)
         savedImgFile.writeBytes(content)
 
         val relativeImgPath = getRelativeImagePath(savingSettings.resourceDir)
-        it.attr("src", FileUtil.join(relativeImgPath, File(url).name))
+        it.attr("src", FileUtil.join(relativeImgPath, File(imgSrc).name))
       }
     }
   }
 
+  private fun getImgUriWithProtocol(imgSrc: String): String {
+    return if (imgSrc.startsWith("file:")) imgSrc
+    else File(imgSrc).toURI().toString()
+  }
+
   private fun getResource(url: String): ByteArray? =
     try {
       HttpRequests.request(url).readBytes(null)