Photo Compress with magick

This is my code for batch compressing tif files in R. The input and output paths are from my USB so please change if you need to.

1. Load the required library
library(magick)

2. Define the paths
input_folder <- "E:/research_projects/IBBL/strumi_mphil/raw_photos/03-03-2026"
output_folder <- "E:/research_projects/IBBL/strumi_mphil/compressed"

3. List all image files in the input folder
image_files <- list.files(input_folder, pattern = "\\.(tif)$", full.names = TRUE)
print("Detected TIFF files:")
print(image_files)


4. Read all images at once
images <- image_read(image_files)
print(class(images))
print(length(images))
print(images)

 (optional) Check if image was read successfully
if (is.null(images) || length(images) == 0) {
  cat("Image not valid or not read correctly:", image_file, "/n")
  next
}

5. Compress all images
compressed_images <- image %>% image_resize("1000x1000>")
print(class(compressed_images))
print(length(compressed_images))


6. Save each compressed image to the output folder
for (i in 1:length(compressed_images)) 
  {original_name <- tools::file_path_sans_ext(basename(image_files[i]))
  cleaned_name <- gsub("_ch00", "", original_name)
  output_filename <- paste0(cleaned_name, "-resize.tif")
  output_path <- file.path(output_folder, output_filename)
  image_write(compressed_images[i], path = output_path, quality = 1000)}

I made this code back in August (I think) and up until now it has run smoothly even when I am compressing 30+ images.

In the past few weeks when I run the code up to step 4, the following error occurs:

rsession-utf8.exe: Read error on strip 901; got 15020 bytes, expected 15264. `TIFFFillStrip' @ error/tiff.c/TIFFErrors/528

This has not happened before. I don’t know if it’s because my laptop is running out of memory or if there is something wrong with the file.