You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用R语言批量将文件夹中的PNG文件转换为WebP格式?

批量将PNG转换为WebP的解决方案

原代码问题分析

  • 第一次尝试的代码中,future_map的.x参数留空,存在语法错误;且两次分离的future_map无法将读取的图片对象与对应的WebP目标文件名一一匹配,导致批量执行失败。
  • 初始批量代码中,readPNG和target均硬编码为单个文件路径,循环时每次都处理同一个文件,无法实现批量转换。

正确实现代码

方法1:使用furrr::future_map2配对处理

这种方法将PNG源路径和WebP目标路径一一对应,并行处理每一对文件:

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

# 设置并行计算(可选,根据CPU核心数调整)
plan(multisession)

# 获取所有PNG文件的完整路径
png_files <- list.files(
  path = getwd(),
  pattern = "\\.png$",  # 正则匹配结尾为.png的文件,避免误匹配其他带png字样的文件
  full.names = TRUE
)

# 生成对应的WebP目标文件名
webp_files <- str_replace(png_files, "\\.png$", ".webp")

# 并行批量转换
future_map2(
  .x = png_files,
  .y = webp_files,
  .f = function(png_path, webp_path) {
    img <- readPNG(png_path)
    write_webp(image = img, target = webp_path, quality = 80)
  }
)

方法2:使用furrr::future_map结合匿名函数

如果不想生成单独的目标文件名向量,也可以在匿名函数中直接处理路径转换:

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

plan(multisession)

png_files <- list.files(
  path = getwd(),
  pattern = "\\.png$",
  full.names = TRUE
)

future_map(png_files, function(png_path) {
  webp_path <- str_replace(png_path, "\\.png$", ".webp")
  img <- readPNG(png_path)
  write_webp(image = img, target = webp_path, quality = 80)
})

关键注意事项

  • 正则表达式修正:使用\\.png$替代原代码的*.png,确保只匹配以.png结尾的文件,避免误匹配无关文件。
  • 并行计算配置:plan(multisession)开启多进程并行,若不需要并行,可替换为plan(sequential),或直接使用purrr::map替代future_map/future_map2。
  • 文件路径对应:确保每个PNG文件都能正确生成对应的WebP路径,避免文件名冲突或路径错误。

内容的提问来源于stack exchange,提问作者MYaseen208

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 17:40:21