0

I have an org-babel code block that returns a base64 encoded image as a string. How can I display that as an inline image?

Currently, I am saving that data to a file as a png, and using :results file :file <path> as the header-args for the babel code block in order to display that image inline. But I'd like to avoid this extra configuration step for certain code blocks. I don't mind the extra configuration if I don't have to keep saving these files to disk.

0

1 Answer 1

0

I think the reason why displaying image data directly is not supported, is because org is meant to be used as pure text files. Adding the data directly to the file would 'pollute' the org file (although I would say that there could be a case for including support for displaying 'svg' data directly). However, if you'd really like to include the data in the org file, then of course solutions can be found.

A similar question has been answered very elaborately already here.

Another potential answer to the solution probably can be found in this repo, although I can not get it to work (in a simple way). (Be sure to check out his el-easydraw package, it looks great!)

In case you prefer a 'simpler' (slightly less perfect) solution, then you could first include the header arguments :results raw and then use the following command (using M-x, or you could make a nice keybinding for it), while placing your cursor somewhere inside the code block (i.e. you can use it directly after evaluating the code block):

(defun my-org-babel-display-base64-image ()
  (interactive)
  (goto-char (org-babel-where-is-src-block-result))
  (forward-line)
  (let* ((result (org-element-at-point-no-context))
         (beg (org-element-property :contents-begin result))
         (end (org-element-property :contents-end result))
         (image (create-image
                 (base64-decode-string (buffer-substring-no-properties beg (1- end)))
                 'png t)))
    (put-text-property beg end 'display image)))

Be sure to set the correct image-type in the image form (here 'png).

This only works for displaying the image, and won't work for exporting.

If you'd like to hack a little more, then you could find a solution to conditionally execute this code automatically (i.e. make sure that the output is a 64base image string) from the org-babel-after-execute-hook.

Not the answer you're looking for? Browse other questions tagged or ask your own question.