rpngwebp

Converting all png files from a folder to webp


I can convert a single file from png format to webp using the following command:

library(png)
library(webp)

write_webp(
    image   = readPNG("fig1.png")
  , target  = "fig1.webp"
  , quality = 80
  )

Wondering how to convert all png files from a folder to webp using the R code something like below:

library(furrr)

list.files(
    path       = getwd()
  , pattern    = "*.png"
  , full.names = TRUE
  ) |> 
  future_map(
      .x      = 
    , .f      = write_webp
    , image   = readPNG("fig1.png")
    , target  = "fig1.webp"
    , quality = 80
    )

Edited

The following code is working for one .png file but don't work for more than one. Any hint please.

library(png)
library(webp)
library(furrr)
library(stringr)

FileNames <-
  list.files(
      path       = getwd()
    , pattern    = "*.png"
    , full.names = FALSE
    ) %>% 
    str_remove(
        string  = .
      , pattern = ".png"
      ) %>% 
    paste0(., ".webp")

FileNames

list.files(
    path       = getwd()
  , pattern    = "*.png"
  , full.names = TRUE
  ) %>% 
  future_map(
      .x        = 
    , .f        = readPNG
      ) %>%
  future_map(
      .x      = 
    , .f      = write_webp
    , target  = FileNames
    , quality = 80
      )

Solution

  • You could use a sapply to apply the function over a vector of files names. To make sure that the target is every time with the .webp extension you could use the file_path_sans_ext function to get the name without .png extension like this:

    library(png)
    library(webp)
    
    setwd("/Users/quinten/Downloads/test_folder_webp")
    files <- dir(pattern = "png$")
    
    sapply(files, \(x) {
      write_webp(
        image   = readPNG(x)
        , target  = paste0(tools::file_path_sans_ext(x),".webp")
        , quality = 80
      )
    })
    

    Created on 2023-10-25 with reprex v2.0.2

    When you check your folder you will see that the target files have been converted.