2016-08-20 49 views
3

我在我的bookdown项目(或者rmarkdown网站,我认为并不重要)中有一个很大的(〜14MB)*.jpeg。 这是一个外部的静态图像,并未被R(到目前为止)所触及。我如何重新缩放本地图像的bookdown/rmarkdown网站?

我打电话的图片,像这样:

```{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") 
``` 

我也通过opts_knit$set(fig.retina = 2)设置视网膜。

我真的不在乎PDF有多大,但很显然,网站上的〜14MB图片相当糟糕。

有没有一种方式,knitr()rmarkdown()bookdown()工具链的一些元素可以自动重新调整图像到指定的,适当的决议?

我天真地假设,如果既out.widthdpi中指定,该图像将被重新缩放(即:更小的文件大小)的窗帘后面,但要么不出现这样的情况,或我我错用了它

Ps .:据我所知,有可能指定一个dpi,然后knitr找出合适的大小;这不是我关心的问题。我想,有点,

+0

是您创建的情节产生的JPEG图像?或者它是一个正在导入的静态外部图像? –

+0

后者,实际上只是来自相机的一些JPEG图像。将更新以澄清。 – maxheld

回答

4

我认为调整的实际图像尺寸(而不是它是多么的HTML缩放)的唯一方法是将图像加载到R和光栅处理了:改编自

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

(光栅化方法:How to set size for local image using knitr for markdown?

这将导致一个较小的图像/ HTML文件。

+0

谢谢!我在github上添加了各自的[功能请求](https://github.com/yihui/knitr/issues/1273);让我们看看@易辉是否认为这是一件有价值的事情。 – maxheld

0

我现在还实现了压缩平原R中的重新缩放功能。它不是很快,它可能很笨拙,但它完成了工作。

library(jpeg) 
library(imager) 

resize_n_compress <- function(file_in, file_out, xmax = 1920, quality = 0.7, cutoff = 100000) { 
    # xmax <- 1920 # y pixel max 
    # quality <- 0.7 # passed on to jpeg::writeJPEG() 
    # cutoff <- 100000 # files smaller than this will not be touched 
    # file_out <- "test.jpg" 
    if (file.size(file_in) < cutoff) { # in this case, just copy file 
    if (!(file_in == file_out)) { 
     file.copy(from = file_in, to = file_out, overwrite = TRUE) 
    } 
    } else {# if larger than cutoff 
    image_raw <- imager::load.image(file = file_in) 
    if (dim(image_raw)[1] > xmax) { # resize only when larger 
     x_pix <- xmax # just in case we want to calculate this, too at some point 
     x_factor <- xmax/dim(image_raw)[1] 
     y_pix <- round(dim(image_raw)[2] * x_factor) 
     image_resized <- imager::resize(im = image_raw, size_x = x_pix, size_y = y_pix) 
    } else {# otherwise take raw 
     image_resized <- image_raw 
    } 
    saveme <- imager:::convert.im.toPNG(A = image_resized) 
    jpeg::writeJPEG(image = saveme, target = file_out, quality = quality) # this overwrites by default 
    } 
} 

也可参阅knitrblogdown这些相关的问题。