2

How can I determine the width of an image of the imagemagick type?


I am inserting an image into a buffer, whose size is (initally) completely unknown to me. I do it more or less like this:

(insert-image (create-image image-data 'imagemagick t))

However, sometimes the image is huge, so I need to limit its size like this:

(insert-image (create-image image-data 'imagemagick t :width 200))

The problem is, sometimes the image is small, and forcing it to have width 200 is very undesirable. So I would like to check the width of the image, and do something like this:

(let ((image (create-image image-data 'imagemagick t)))
  (if (> (image-width image) 200)
      (append image '(:width 200))
    image))

but I don't know how to get the width of an image in order to make this check. Is there anything similar to a image-width function?

3

See the documentation on the function image-size:

image-size is a built-in function in `C source code'.

(image-size SPEC &optional PIXELS FRAME)

Return the size of image SPEC as pair (WIDTH . HEIGHT). PIXELS non-nil means return the size in pixels, otherwise return the size in canonical character units. FRAME is the frame on which the image will be displayed. FRAME nil or omitted means use the selected frame.

In general, you can find the documentation of a function by doing C-h f function-name-here. You can try guessing the name of the function if you don't know if it exists. The names are pretty sane, and once you narrow down a prefix, you can always press <tab> to show a list.

3

@PythonNut is correct that (image-size) is the function you are looking for. With it, you can extract the height and width from an image in image-mode like so:

(let* ((image-dimensions (image-size (image-get-display-property) :pixels))
         (width (car image-dimensions))
         (height (cdr image-dimensions))
  ...))

For example and maybe on a related/useful note, I use this approach to put the image dimensions in the mode line when viewing an image:

(defun show-image-dimensions-in-mode-line ()
  (let* ((image-dimensions (image-size (image-get-display-property) :pixels))
         (width (car image-dimensions))
         (height (cdr image-dimensions)))
    (setq mode-line-buffer-identification
          (format "%s %dx%d" (propertized-buffer-identification "%12b") width height))))

(add-hook 'image-mode-hook #'show-image-dimensions-in-mode-line)

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.