maxheld maxheld - 3 months ago 24
R Question

How do I rescale local images for bookdown / rmarkdown website?

I have a pretty big (~14MB)

*.jpeg
in my bookdown project (or rmarkdown website, doesn't really matter, I think).
This is an external, static image, not touched by R (so far).

I'm calling the picture like so:

```{r q-pic, echo=FALSE, out.width="100%", fig.cap="Q-Sorting during the 2016 CiviCon", dpi = 72}
include_graphics(path = "img/q-sorting3.jpg")
```


I've also set retina via
opts_knit$set(fig.retina = 2)
.

I don't really care how huge the PDF is, but obviously, a ~14MB image on a website is pretty bad.

Is there a way that some element of the
knitr()
rmarkdown()
bookdown()
toolchain can automatically rescale images to a specified, appropriate resolution?

I naively assumed that if both
out.width
and
dpi
were specified, that the image would be rescaled (ie.: smaller file size) behind the curtains, but that either appears not to be the case, or I'm using it wrong.

Ps.: I understand that there's a possibility to specifiy a
dpi
and then have
knitr
figure out an appropriate size; that's not my concern. I'd like, sort of, the inverse of that.

Answer

I think the only way to adjust the actual image size (and not just how it is scaled in the HTML) is to load the image into R and rasterize it:

```{r fig.width=3}
library(jpeg)
library(grid)
img <- readJPEG("test.jpg")
grid.raster(img)
```

(Rasterization approach adapted from: How to set size for local image using knitr for markdown?)

This will result in a smaller image/HTML file.