2016-08-20 107 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這些相關的問題。