Reputation: 5891
I have a directory full of 100 .png images I'd like to convert to pdf.
The images are exactly the size I want the pdf to be.
I can create a multi-page pdf using magick
"manually" like this:
library(magick)
img1 <- image_read("image1.png")
img2 <- image_read("image2.png")
image_write(c(img1, img2), format = "pdf", "check.pdf")
But I'm having trouble getting the image_write command to accept a vector of filenames to automate this process. For example, I'd like to make a 100-page pdf from the .png images in my directory "test":
all_images <- list.files("test")
I thought that purrr
might help but no luck:
library(purrr)
image_write(map(all_images, image_read), format = "pdf", "check.pdf")
Any ideas?
Upvotes: 4
Views: 5868
Reputation: 3993
magick::image_*()
functions are vectorized. So you can do:
dir = '/path/to/dir'
fl = list.files(dir, full.names = TRUE, pattern = '.png')
# magick
img = image_read(fl) # read from vector of paths
img2 = image_append(img, stack = TRUE) # places pics above one another
image_write(img2, file.path(dir, 'check.pdf'))
This places the images above one another, yet not on single pages.
Upvotes: 2
Reputation: 6116
You need to concatenate different "magick-image
objects using c
.
It's the same as doing c(img1,img2,img3,...)
all_images_1 <- purrr::reduce(
purrr::map(all_images,image_read),
c
)
image_write(all_images_1 , format = "pdf", "check.pdf")
Upvotes: 4