Plot a JPG image using base graphics in R

Here goes an updated solution, that relies only on the jpeg package and handles color and greyscale images (packages used in other solutions are outdated and won't install with a recent R version).

The solution consists in this plot function:

plot_jpeg = function(path, add=FALSE)
{
  require('jpeg')
  jpg = readJPEG(path, native=T) # read the file
  res = dim(jpg)[2:1] # get the resolution, [x, y]
  if (!add) # initialize an empty plot area if add==FALSE
    plot(1,1,xlim=c(1,res[1]),ylim=c(1,res[2]),asp=1,type='n',xaxs='i',yaxs='i',xaxt='n',yaxt='n',xlab='',ylab='',bty='n')
  rasterImage(jpg,1,1,res[1],res[2])
}

This function can then be called with the path of the picture as argument, for example:

plot_jpeg('~/nyancat.jpg')

To add the picture to an existing plot, use the switch add=TRUE - and be wary of axis limits!


Using the imager package:

library(imager)

image <- load.image(image_filename)
plot(image)

This works for a number of image formats including jpeg, gif, etc...

Tags:

R