Skip to content

Instantly share code, notes, and snippets.

@richarddmorey
Last active May 13, 2022 11:25
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save richarddmorey/9d04f29026abb217748311d806063136 to your computer and use it in GitHub Desktop.
Save richarddmorey/9d04f29026abb217748311d806063136 to your computer and use it in GitHub Desktop.
Create image covers for PDFs
#' Create cover images for talks from a folder of PDFs
#'
#' Requires imagemagick to be installed and in the path for the convert command
#' @param pdf_dir Directory containing PDF files of papers
#' @param img_dir Directory to output all the image files
#' @param crop_height How big to make the cropped images, relative to full page
#' @param fade_height How much of the image to fade to transparent at the bottom
#' @param density resolution for PNG images
#'
create_covers = function(pdf_dir, img_dir, crop_height = .5, fade_height = .25, density = 300){
if(!dir.exists(file.path(img_dir,'covers')))
dir.create(file.path(img_dir,'covers'))
dir(pdf_dir, full.names = TRUE, pattern = '*.pdf') %>%
purrr::walk(function(fn){
basename(fn) %>%
tools::file_path_sans_ext() -> fn0
img = magick::image_read_pdf(fn, pages = 1, density = density)[1]
# Full cover
magick::image_write(
image = img,
path = glue::glue('{img_dir}/covers/{fn0}_cover.png'),
format = "png", density = density
)
# Cropped
img_height = magick::image_info(img)$height
magick::image_crop(img, glue::glue('x{img_height*crop_height}')) %>%
image_write(
path = glue::glue('{img_dir}/covers/{fn0}_cover_cropped.png'),
format = "png", density = density
)
})
## Add fade effect to all cropped images
## I like to display these with css:
## .img-cover {
## width:90%;
## border-right: solid 1px black;
## border-left: solid 1px black;
## border-top: solid 1px black;
## }
## which will add black borders to the right, left,
## and bottom.
glue::glue('{img_dir}/covers') %>%
dir(pattern = '*_cover_cropped.png', full.names = TRUE) %>%
purrr::walk(function(fn){
magick::image_read(fn) %>%
magick::image_info() %>%
`$`('height') -> img_height
fn0 = tools::file_path_sans_ext(fn)
glue::glue('convert {fn0}.png -alpha set -background none -channel A -sparse-color barycentric "0,%[h] none 0,{img_height*(1-fade_height)} white" +channel {fn0}_fade.png') %>%
system()
})
}
## Example:
# create_covers('readings', 'img')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment