Skip to content

Instantly share code, notes, and snippets.

@DavZim
Last active March 26, 2019 08:46
Show Gist options
  • Save DavZim/8602875652752f293bc7224cba1014d6 to your computer and use it in GitHub Desktop.
Save DavZim/8602875652752f293bc7224cba1014d6 to your computer and use it in GitHub Desktop.
library(imager)          # for loading and plotting of the PNG file
library(glue)            # for string parsing
library(png)             # alternative for image loading

take_screenshot <- function(file = "screenshot.png", force_imagemagick = FALSE) {
  
  if (Sys.info()[["sysname"]] == "Linux" && 
      as.numeric(system("cat /var/log/dpkg.log | grep scrot | wc -l", intern = TRUE)) > 0 &&
      !force_imagemagick) {
    cmd <- "scrot --silent"
  } else {
    cmd <- "import -silent -window root"
  }
  system(glue::glue("{cmd} {file}"))
}

capture_screen_imager <- function(xmin = 0, xmax = Inf, ymin = 0, ymax = Inf, force_imagemagick = FALSE) {
  tmp <- tempfile(fileext = ".png")
  take_screenshot(tmp, force_imagemagick)
  
  img <- load.image(tmp)
  a <- try(unlink(tmp))
  imsub(img, x >= xmin, x <= xmax, y >= ymin, y <= ymax)
}

capture_screen_png <- function(xmin = 0, xmax = Inf, ymin = 0, ymax = Inf, force_imagemagick = FALSE) {
  tmp <- tempfile(fileext = ".png")
  take_screenshot(tmp, force_imagemagick)
  
  img <- png::readPNG(tmp)
  a <- try(unlink(tmp))
  
  d <- dim(img)
  img[max(1, xmin):min(d[1], xmax), 
      max(1, ymin):min(d[2], ymax),
      ]
}

Benchmarking

library(microbenchmark)  # for benchmarking the different versions

microbenchmark(
  imager_igck  = capture_screen_imager(force_imagemagick = TRUE),
  png_igck     = capture_screen_png(force_imagemagick = TRUE),
  imager_scrot = capture_screen_imager(force_imagemagick = FALSE),
  png_scrot    = capture_screen_png(force_imagemagick = FALSE),
  times  = 10
)
#> Unit: milliseconds
#>          expr       min        lq      mean    median        uq       max
#>   imager_igck 1038.8447 1094.7961 1114.2786 1115.4022 1149.1751 1176.3249
#>      png_igck  416.3371  430.4285  474.1721  491.0695  496.0571  516.2001
#>  imager_scrot  892.5448  986.4270  997.3108  991.4439  994.1008 1162.1830
#>     png_scrot  278.4057  287.3587  314.1715  306.2184  347.9310  358.1646
#>  neval
#>     10
#>     10
#>     10
#>     10

Result

the fastest image screenshot is using scrot (sudo apt install scrot) using

system(glue::glue("scrot --silent screenshot.png"))
img <- png::readPNG("screenshot.png")
dim(img)
#> [1] 1080 1920    3

Created on 2019-03-26 by the reprex package (v0.2.1)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment