In almost all cases, I want to see JPEGs such as photos scaled to the current buffer size. This is the default with image-mode. However, for PNG files, primarity screenshots, I want to view them without scaling by default.

How do I best assign scaling behavior based on file type?

By the way, image-mode is not a requirement. I am fine with switching to something else.


Based on Jordon Biondo's answer, I am now using the following setup:

(defun my-image-mode-hook ()
  (when (and (display-images-p) (eq image-type 'imagemagick))
    (let ((extension (downcase (file-name-extension
      (when (string-match-p "^\\(png\\|gif\\|bmp\\)$" extension)
        (image-transform-set-scale 1)
        (setq image-transform-resize nil)))))
(add-hook 'image-mode-hook 'my-image-mode-hook)

This never scales images of type PNG, GIF, or BMP. All other images are scaled, as per default, to fit into the buffer. To prevent additional scaling based on selected font size, I have customized:

'(image-scaling-factor 1)

Two methods would be useful to you image-transform-fit-to-width and image-transform-set-scale, you can use these two functions inside a image-mode-hook to setup the display like you want based on the file. You can get the file extension by using file-name-extension on buffer-file-name.

Here is an implementation:

(defun my-image-mode-setup ()
  (when (and (display-images-p ) (eq image-type 'imagemagick))
    (pcase (downcase (file-name-extension (buffer-file-name)))
      ;; when jpg, fit image to buffer width
      ((or "jpg" "jpeg") (image-transform-fit-to-width))
      ;; when png, scale the image to 100%
      ((or "png") (image-transform-set-scale 1)))))

(add-hook 'image-mode-hook 'my-image-mode-setup)

Since Emacs 27, imagemagick is deprecated, so the values of image-type have changed. Testing the extension is usually no longer necessary:

(defun my-image-mode-setup ()
  (when (and (display-images-p)
             (memq image-type '(gif png)))
    (image-transform-set-scale 1)
    (setq image-transform-resize nil)))

(add-hook 'image-mode-hook #'my-image-mode-setup)

  • That's pretty nice! It would be even better if JPEGs could be made to always fit in the buffer, by width and height. (default behavior)
    – feklee
    Feb 6 '19 at 21:39
  • On my display PNG images are still scaled up somewhat. The scaling seems to be proportional to the default font size. As I found out, to prevent that, one needs to (setq image-scaling-factor 1).
    – feklee
    Feb 7 '19 at 15:02

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.