一个快速添加水印的R语言脚本

随想录  ·  2025-03-01

今天,正好有一个工作,是要为多张图片添加一个水印。于是便借助AI的智慧,为我生成了以下代码。

install.packages("magick")
library(magick)

# 设置输入和输出文件夹
input_folder <- "D:/个人/watermark/input_images"
output_folder <- "D:/个人/watermark/output_images"

# 加载水印图片
watermark_path <- "D:/个人/watermark/watermark.png"
watermark <- image_read(watermark_path)


# 获取所有图片文件
files <- list.files(input_folder, pattern = "\\.jpg$", full.names = TRUE)

# 打印调试信息
print(paste("Found", length(files), "images to process."))

# 循环处理每张图片
for (file in files) {
  # 加载图片
  print(paste("Processing:", file))
  img <- image_read(file)
  
  if (is.null(img)) {
    print(paste("Failed to load image:", file))
    next
  }
  
  # 获取图片宽度
  img_info <- image_info(img)
  img_width <- img_info$width
  
  # 水印宽度
  watermark_info <- image_info(watermark)
  watermark_width <- watermark_info$width
  
  # 计算右上角偏移量
  right_margin <- 200  # 距离右边缘的像素数(可以根据需要调整)
  top_margin <- 200    # 距离上边缘的像素数(可以根据需要调整)
  
  offset_x <- img_width - watermark_width - right_margin  # 水平偏移量
  offset_y <- top_margin                                  # 垂直偏移量
  
  # 添加水印到右上角
  img_with_watermark <- image_composite(
    image = img,
    watermark,
    offset = paste("+", offset_x, "+", offset_y, sep = "")
  )
  
  # 保存结果
  output_file <- file.path(output_folder, basename(file))
  image_write(img_with_watermark, output_file, format = "jpg")
  
  print(paste("Saved:", output_file))
}
评论
随想录. All Rights Reserved. Theme Jasmine by Kent Liao.