Function: image-convert

image-convert is a byte-compiled function defined in image-converter.el.gz.

Signature

(image-convert IMAGE &optional IMAGE-FORMAT)

Documentation

Convert IMAGE to an image format which Emacs understands.

This will usually be "png", but is controlled by the value of the image-convert-to-format user option.

IMAGE can either be a file name, an image object returned by create-image, or a string with image data. In the latter case, IMAGE-FORMAT should be a symbol whose name is a MIME specification of image format, such as "image/webp". For instance:

  (image-convert data-string 'image/bmp)

This function converts the image to the preferred format, per the value of image-convert-to-format, and returns the converted image data as a string.

Source Code

;; Defined in /usr/src/emacs/lisp/image/image-converter.el.gz
(defun image-convert (image &optional image-format)
  "Convert IMAGE to an image format which Emacs understands.
This will usually be \"png\", but is controlled by the value
of the `image-convert-to-format' user option.

IMAGE can either be a file name, an image object returned
by `create-image', or a string with image data.  In the latter
case, IMAGE-FORMAT should be a symbol whose name is a MIME
specification of image format, such as \"image/webp\".
For instance:

  (image-convert data-string \\='image/bmp)

This function converts the image to the preferred format, per
the value of `image-convert-to-format', and returns the
converted image data as a string."
  (image-converter-initialize)
  (unless image-converter
    (error "No external image converters available"))
  (when (and image-format
             (not (= (length (split-string (symbol-name image-format) "/")) 2)))
    (error "IMAGE-FORMAT should be a symbol like `image/png'"))
  (with-temp-buffer
    (set-buffer-multibyte nil)
    (let* ((source (if (listp image)
                       (plist-get (cdr image) :file)
                     image))
           (format (if (listp image)
                       (plist-get (cdr image) :data-p)
                     image-format))
           (type (if format
                     (image-converter--mime-type format)
                   (file-name-extension source)))
           (extra-converter (gethash type image-converter--extra-converters)))
      (if extra-converter
          (funcall extra-converter source format)
        (when-let ((err (image-converter--convert
                         image-converter source format)))
          (error "%s" err))))
    (if (listp image)
        ;; Return an image object that's the same as we were passed,
        ;; but ignore the :type value.
        (apply #'create-image (buffer-string)
               (intern image-convert-to-format)
               t
               (cl-loop for (key val) on (cdr image) by #'cddr
                        unless (eq key :type)
                        append (list key val)))
      (buffer-string))))