Reputation: 103
I have a excel list of sentences and I am trying to annotate each one onto the same template image and save each image file individually (i.e. I will have 20 images, with the same background but different text - akin to Word's Mail Merge feature with documents).
To do this, I am using the R package magick
's image_annotate
and image_write
commands. My assumption was that putting it into a for
loop would accomplish this task.
I used the following code:
QuoteList=read.csv("wordlist.csv", stringsAsFactors = F, header = T)
myTemplate=image_read("template.png")
for (i in 1:nrow(QuoteList))
{
thisImage[i]=image_annotate(myTemplate, QuoteList$myquote[i])
image_write(thisImage[i], format = "png")
}
However I get the error:
Error in magick_image_replace(x, i, value) : subscript out of bounds
I am not entirely sure what I am doing wrong and would highly appreciate any help on this or any possible alternative solutions. Thanks in advance.
Upvotes: 1
Views: 1058
Reputation: 643
You need to replace the object you're writing with each iteration, but write to a new filename each time:
for (i in 1:nrow(QuoteList)){
thisImage = image_annotate(myTemplate, QuoteList$myquote[i])
image_write(thisImage, format <- "png", path = paste0(i, ".png"))
}
Upvotes: 1