Am wondering if anyone can tell me what I'm doing wrong. Basically the commented out code fails.. thanks

(let* ((img-file "/tmp/x.png")
       (img-str (with-temp-buffer (insert-file-contents img-file) (buffer-string)))
       ;; (img (create-image img-str 'png))) ; inserts a small empty box
       (img (create-image img-file 'png)))   ; correctly inserts image
  (image-flush img)
  (insert-image img))

create-image can handle both images created from a file (represented as a path string) and data (represented as a binary string). Consider that it can't tell what your intention was from a string alone and it's obvious what the issue is, you must call it in a way making clear that this is inline data we're dealing with, not a file. For this you just use the third argument with a boolean value, defaulting to nil.

Another issue is that Emacs assumes strings are multi-byte by default, thereby allowing for encodings such as UTF-8. This is not what you'd want for an image as it's just bytes. Also, I'd recommend to disable any unnecessary coding conversions in any case with insert-file-contents-literally:

(let* ((img-file "/tmp/x.png")
       (img-str (with-temp-buffer
                  (set-buffer-multibyte nil)
                  (insert-file-contents-literally img-file)
       (img (create-image img-str 'png)))
  (image-flush img)
  (insert-image img))
| improve this answer | |
  • From the docs, I see: (create-image FILE-OR-DATA &optional TYPE DATA-P &rest PROPS) and it says: Optional DATA-P non-nil means FILE-OR-DATA is a string containing image data. Tried adding t, but still get the same issue: (img (create-image img-str 'png t)) – RoyM Mar 21 '19 at 22:51
  • Indeed, I've tried myself now and discovered there's one more thing to do. – wasamasa Mar 22 '19 at 6:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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